2 * This module contains the implementation of the C++ header generation available through
3 * the command line switch -Hc.
5 * Copyright: Copyright (C) 1999-2023 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
14 import core
.stdc
.stdio
;
15 import core
.stdc
.string
;
16 import core
.stdc
.ctype
;
18 import dmd
.astcodegen
;
20 import dmd
.arraytypes
;
27 import dmd
.identifier
;
29 import dmd
.root
.filename
;
33 import dmd
.common
.outbuffer
;
38 // Generate asserts to validate the header
39 //debug = Debug_DtoH_Checks;
42 * Generates a C++ header containing bindings for all `extern(C[++])` declarations
43 * found in the supplied modules.
49 * - the header is written to `<global.params.cxxhdrdir>/<global.params.cxxhdrfile>`
50 * or `stdout` if no explicit file was specified
51 * - bindings conform to the C++ standard defined in `global.params.cplusplus`
52 * - ignored declarations are mentioned in a comment if `global.params.doCxxHdrGeneration`
53 * is set to `CxxHeaderMode.verbose`
55 extern(C
++) void genCppHdrFiles(ref Modules ms
)
63 // enable indent by spaces on buffers
69 scope v
= new ToCppBuffer(&fwd
, &done
, &decl
);
71 // Conditionally include another buffer for sanity checks
72 debug (Debug_DtoH_Checks
)
75 check
.doindent
= true;
87 if (global
.params
.cxxhdr
.fullOutput
)
88 buf
.printf("// Automatically generated by %s Compiler v%d", global
.compileEnv
.vendor
.ptr
, global
.versionNumber());
90 buf
.printf("// Automatically generated by %s Compiler", global
.compileEnv
.vendor
.ptr
);
94 buf
.writestringln("#pragma once");
96 hashInclude(buf
, "<assert.h>");
97 hashInclude(buf
, "<math.h>");
98 hashInclude(buf
, "<stddef.h>");
99 hashInclude(buf
, "<stdint.h>");
100 // buf.writestring(buf, "#include <stdio.h>\n");
101 // buf.writestring("#include <string.h>\n");
103 // Emit array compatibility because extern(C++) types may have slices
104 // as members (as opposed to function parameters)
106 #ifdef CUSTOM_D_ARRAY_TYPE
107 #define _d_dynamicArray CUSTOM_D_ARRAY_TYPE
109 /// Represents a D [] array
111 struct _d_dynamicArray final
116 _d_dynamicArray() : length(0), ptr(NULL) { }
118 _d_dynamicArray(size_t length_in, T *ptr_in)
119 : length(length_in), ptr(ptr_in) { }
121 T& operator[](const size_t idx) {
122 assert(idx < length);
126 const T& operator[](const size_t idx) const {
127 assert(idx < length);
136 hashIf(buf
, "!defined(_d_real)");
138 hashDefine(buf
, "_d_real long double");
143 // buf.writestringln("// fwd:");
148 // buf.writestringln("// done:");
151 // buf.writestringln("// decl:");
154 debug (Debug_DtoH_Checks
)
156 // buf.writestringln("// check:");
160 size_t getSlotNumber(int dummy, ...)
166 void *f = va_arg(ap, void*);
167 for (size_t i = 0; ; i++)
169 if ( (*(void***)&c)[i] == f)
185 // prevent trailing newlines
187 while (buf
.length
>= 4 && buf
[$-4..$] == "\r\n\r\n")
188 buf
.remove(buf
.length
- 2, 2);
190 while (buf
.length
>= 2 && buf
[$-2..$] == "\n\n")
191 buf
.remove(buf
.length
- 1, 1);
194 if (global
.params
.cxxhdr
.name
is null)
196 // Write to stdout; assume it succeeds
197 size_t n
= fwrite(buf
[].ptr
, 1, buf
.length
, stdout
);
198 assert(n
== buf
.length
); // keep gcc happy about return values
202 const(char)[] name
= FileName
.combine(global
.params
.cxxhdr
.dir
, global
.params
.cxxhdr
.name
);
203 if (!writeFile(Loc
.initial
, name
, buf
[]))
210 /****************************************************
211 * Visitor that writes bindings for `extern(C[++]` declarations.
213 extern(C
++) final class ToCppBuffer
: Visitor
215 alias visit
= Visitor
.visit
;
226 /// Namespace providing the actual AST nodes
227 alias AST
= ASTCodegen
;
232 /// Forward declared nodes (which might not be emitted yet)
233 bool[void*] forwarded
;
235 /// Buffer for forward declarations
238 /// Buffer for integrity checks
239 debug (Debug_DtoH_Checks
) OutBuffer
* checkbuf
;
241 /// Buffer for declarations that must emitted before the currently
242 /// visited node but can't be forward declared (see `includeSymbol`)
245 /// Default buffer for the currently visited declaration
248 /// The generated header uses `real` emitted as `_d_real`?
251 /// The generated header should contain comments for skipped declarations?
252 const bool printIgnored
;
254 /// State specific to the current context which depends
255 /// on the currently visited node and it's parents
256 static struct Context
258 /// Default linkage in the current scope (e.g. LINK.c inside `extern(C) { ... }`)
259 LINK linkage
= LINK
.d
;
261 /// Enclosing class / struct / union
262 AST
.AggregateDeclaration adparent
;
264 /// Enclosing template declaration
265 AST
.TemplateDeclaration tdparent
;
267 /// Identifier of the currently visited `VarDeclaration`
268 /// (required to write variables of funtion pointers)
271 /// Original type of the currently visited declaration
274 /// Last written visibility level applying to the current scope
275 AST
.Visibility
.Kind currentVisibility
;
277 /// Currently applicable storage classes
278 AST
.STC storageClass
;
280 /// How many symbols were ignored
283 /// Currently visited types are required by another declaration
284 /// and hence must be emitted
287 /// Processing a type that can be forward referenced
290 /// Inside of an anonymous struct/union (AnonDeclaration)
291 bool inAnonymousDecl
;
294 /// Informations about the current context in the AST
297 // Generates getter-setter methods to replace the use of alias this
298 // This should be replaced by a `static foreach` once the gdc tester
299 // gets upgraded to version 10 (to support `static foreach`).
300 private extern(D
) static string
generateMembers() @safe
303 foreach(member
; __traits(allMembers
, Context
))
305 result
~= "ref auto " ~ member
~ "() { return context." ~ member
~ "; }\n";
309 mixin(generateMembers());
311 this(OutBuffer
* fwdbuf
, OutBuffer
* donebuf
, OutBuffer
* buf
) scope
313 this.fwdbuf
= fwdbuf
;
314 this.donebuf
= donebuf
;
316 this.printIgnored
= global
.params
.cxxhdr
.fullOutput
;
320 * Emits `dsym` into `donebuf` s.t. it is declared before the currently
321 * visited symbol that written to `buf`.
323 * Temporarily clears `context` to behave as if it was visited normally.
325 private void includeSymbol(AST
.Dsymbol dsym
)
329 printf("[includeSymbol(AST.Dsymbol) enter] %s\n", dsym
.toChars());
330 scope(exit
) printf("[includeSymbol(AST.Dsymbol) exit] %s\n", dsym
.toChars());
333 auto ptr
= cast(void*) dsym
in visited
;
337 // Temporary replacement for `buf` which is appended to `donebuf`
339 decl
.doindent
= true;
341 scope (exit
) donebuf
.write(&decl
);
343 auto ctxStash
= this.context
;
344 auto bufStash
= this.buf
;
346 this.context
= Context
.init
;
348 this.mustEmit
= true;
352 this.context
= ctxStash
;
356 /// Determines what kind of enum `type` is (see `EnumKind`)
357 private EnumKind
getEnumKind(AST
.Type type
)
359 if (type
) switch (type
.ty
)
364 AST
.Tchar
, AST
.Twchar
, AST
.Tdchar
,
365 AST
.Tint8
, AST
.Tuns8
,
366 AST
.Tint16
, AST
.Tuns16
,
368 AST
.Tint64
, AST
.Tuns64
:
369 return EnumKind
.Numeric
;
372 return EnumKind
.String
;
375 return EnumKind
.Enum
;
379 return EnumKind
.Other
;
382 /// Determines the type used to represent `type` in C++.
383 /// Returns: `const [w,d]char*` for `[w,d]string` or `type`
384 private AST
.Type
determineEnumType(AST
.Type type
)
386 if (auto arr
= type
.isTypeDArray())
390 case AST
.Tchar
: return AST
.Type
.tchar
.constOf
.pointerTo
;
391 case AST
.Twchar
: return AST
.Type
.twchar
.constOf
.pointerTo
;
392 case AST
.Tdchar
: return AST
.Type
.tdchar
.constOf
.pointerTo
;
399 /// Writes a final `;` and insert an empty line outside of aggregates
400 private void writeDeclEnd() @safe
402 buf
.writestringln(";");
408 /// Writes the corresponding access specifier if necessary
409 private void writeProtection(const AST
.Visibility
.Kind kind
)
411 // Don't write visibility for global declarations
412 if (!adparent || inAnonymousDecl
)
417 switch(kind
) with(AST
.Visibility
.Kind
)
420 if (this.currentVisibility
== AST
.Visibility
.Kind
.private_
)
422 this.currentVisibility
= AST
.Visibility
.Kind
.private_
;
426 case package_
, protected_
:
427 if (this.currentVisibility
== AST
.Visibility
.Kind
.protected_
)
429 this.currentVisibility
= AST
.Visibility
.Kind
.protected_
;
430 token
= "protected:";
433 case undefined
, public_
, export_
:
434 if (this.currentVisibility
== AST
.Visibility
.Kind
.public_
)
436 this.currentVisibility
= AST
.Visibility
.Kind
.public_
;
441 printf("Unexpected visibility: %d!\n", kind
);
446 buf
.writestringln(token
);
451 * Writes an identifier into `buf` and checks for reserved identifiers. The
452 * parameter `canFix` determines how this function handles C++ keywords:
454 * `false` => Raise a warning and print the identifier as-is
455 * `true` => Append an underscore to the identifier
458 * s = the symbol denoting the identifier
459 * canFixup = whether the identifier may be changed without affecting
460 * binary compatibility
462 private void writeIdentifier(const AST
.Dsymbol s
, const bool canFix
= false)
464 if (const mn
= getMangleOverride(s
))
465 return buf
.writestring(mn
);
467 writeIdentifier(s
.ident
, s
.loc
, s
.kind(), canFix
);
470 /** Overload of `writeIdentifier` used for all AST nodes not descending from Dsymbol **/
471 private void writeIdentifier(const Identifier ident
, const Loc loc
, const char* kind
, const bool canFix
= false)
475 void warnCxxCompat(const(char)* reason
)
483 __gshared
bool warned
= false;
484 warning(loc
, "%s `%s` is a %s", kind
, ident
.toChars(), reason
);
488 warningSupplemental(loc
, "The generated C++ header will contain " ~
489 "identifiers that are keywords in C++");
494 if (global
.params
.warnings
!= DiagnosticReporting
.off || canFix
)
496 // Warn about identifiers that are keywords in C++.
497 if (auto kc
= keywordClass(ident
))
500 buf
.writestring(ident
.toString());
505 /// Checks whether `t` is a type that can be exported to C++
506 private bool isSupportedType(AST
.Type t
)
522 return isSupportedType((cast(AST
.TypeNext
) t
).next
);
527 auto tf
= cast(AST
.TypeFunction
) t
;
528 if (!isSupportedType(tf
.next
))
530 foreach (_
, param
; tf
.parameterList
)
532 if (!isSupportedType(param
.type
))
538 // Noreturn has a different mangling
541 // _Imaginary is C only.
542 case AST
.Timaginary32
:
543 case AST
.Timaginary64
:
544 case AST
.Timaginary80
:
551 override void visit(AST
.Dsymbol s
)
556 import dmd
.asttypename
;
557 printf("[AST.Dsymbol enter] %s\n", s
.astTypeName().ptr
);
561 override void visit(AST
.Import i
)
563 debug (Debug_DtoH
) mixin(traceVisit
!i
);
565 /// Writes `using <alias_> = <sym.ident>` into `buf`
566 const(char*) writeImport(AST
.Dsymbol sym
, const Identifier alias_
)
568 /// `using` was introduced in C++ 11 and only works for types...
569 if (global
.params
.cplusplus
< CppStdRevision
.cpp11
)
570 return "requires C++11";
572 if (auto ad
= sym
.isAliasDeclaration())
575 ad
= sym
.isAliasDeclaration();
577 // Might be an alias to a basic type
578 if (ad
&& !ad
.aliassym
&& ad
.type
)
582 // Restricted to types and other aliases
583 if (!sym
.isScopeDsymbol() && !sym
.isAggregateDeclaration())
584 return "only supports types";
586 // Write `using <alias_> = `<sym>`
588 buf
.writestring("using ");
589 writeIdentifier(alias_
, i
.loc
, "renamed import");
590 buf
.writestring(" = ");
591 // Start at module scope to avoid collisions with local symbols
592 if (this.context
.adparent
)
593 buf
.writestring("::");
594 buf
.writestring(sym
.ident
.toString());
599 // Only missing without semantic analysis
600 // FIXME: Templates need work due to missing parent & imported module
604 ignored("`%s` because it's inside of a template declaration", i
.toChars());
608 // Non-public imports don't create new symbols, include as needed
609 if (i
.visibility
.kind
< AST
.Visibility
.Kind
.public_
)
612 // Symbols from static imports should be emitted inline
616 const isLocal
= !i
.parent
.isModule();
618 // Need module for symbol lookup
621 // Emit an alias for each public module member
622 if (isLocal
&& i
.names
.length
== 0)
624 assert(i
.mod
.symtab
);
626 // Sort alphabetically s.t. slight changes in semantic don't cause
627 // massive changes in the order of declarations
628 AST
.Dsymbols entries
;
629 entries
.reserve(i
.mod
.symtab
.length
);
631 foreach (entry
; i
.mod
.symtab
.tab
.asRange
)
633 // Skip anonymous / invisible members
634 import dmd
.access
: symbolIsVisible
;
635 if (!entry
.key
.isAnonymous() && symbolIsVisible(i
, entry
.value
))
636 entries
.push(entry
.value
);
639 // Seperate function because of a spurious dual-context deprecation
640 static int compare(const AST
.Dsymbol
* a
, const AST
.Dsymbol
* b
)
642 return strcmp(a
.ident
.toChars(), b
.ident
.toChars());
644 entries
.sort
!compare();
646 foreach (sym
; entries
)
649 if (auto err
= writeImport(sym
, sym
.ident
))
650 ignored("public import for `%s` because `using` %s", sym
.ident
.toChars(), err
);
655 // Include all public imports and emit using declarations for each alias
656 foreach (const idx
, name
; i
.names
)
658 // Search the imported symbol
659 auto sym
= i
.mod
.search(Loc
.initial
, name
);
660 assert(sym
); // Missing imports should error during semantic
664 // Detect the assigned name for renamed import
665 auto alias_
= i
.aliases
[idx
];
669 if (auto err
= writeImport(sym
, alias_
))
670 ignored("renamed import `%s = %s` because `using` %s", alias_
.toChars(), name
.toChars(), err
);
674 override void visit(AST
.AttribDeclaration pd
)
676 debug (Debug_DtoH
) mixin(traceVisit
!pd
);
678 Dsymbols
* decl
= pd
.include(null);
684 if (adparent || s
.visible().kind
>= AST
.Visibility
.Kind
.public_
)
689 override void visit(AST
.StorageClassDeclaration scd
)
691 debug (Debug_DtoH
) mixin(traceVisit
!scd
);
693 const stcStash
= this.storageClass
;
694 this.storageClass |
= scd
.stc;
695 visit(cast(AST
.AttribDeclaration
) scd
);
696 this.storageClass
= stcStash
;
699 override void visit(AST
.LinkDeclaration ld
)
701 debug (Debug_DtoH
) mixin(traceVisit
!ld
);
704 linkage
= ld
.linkage
;
705 visit(cast(AST
.AttribDeclaration
)ld
);
709 override void visit(AST
.CPPMangleDeclaration md
)
711 debug (Debug_DtoH
) mixin(traceVisit
!md
);
713 const oldLinkage
= this.linkage
;
714 this.linkage
= LINK
.cpp
;
715 visit(cast(AST
.AttribDeclaration
) md
);
716 this.linkage
= oldLinkage
;
719 override void visit(AST
.Module m
)
721 debug (Debug_DtoH
) mixin(traceVisit
!m
);
723 foreach (s
; *m
.members
)
725 if (s
.visible().kind
< AST
.Visibility
.Kind
.public_
)
731 override void visit(AST
.FuncDeclaration fd
)
733 debug (Debug_DtoH
) mixin(traceVisit
!fd
);
735 if (cast(void*)fd
in visited
)
737 // printf("FuncDeclaration %s %s\n", fd.toPrettyChars(), fd.type.toChars());
738 visited
[cast(void*)fd
] = true;
740 // silently ignore non-user-defined destructors
741 if (fd
.isGenerated
&& fd
.isDtorDeclaration())
744 // Note that tf might be null for templated (member) functions
745 auto tf
= cast(AST
.TypeFunction
)fd
.type
;
746 if ((tf
&& (tf
.linkage
!= LINK
.c || adparent
) && tf
.linkage
!= LINK
.cpp
) ||
(!tf
&& fd
.isPostBlitDeclaration()))
748 ignored("function %s because of linkage", fd
.toPrettyChars());
749 return checkFunctionNeedsPlaceholder(fd
);
751 if (fd
.mangleOverride
&& tf
&& tf
.linkage
!= LINK
.c
)
753 ignored("function %s because C++ doesn't support explicit mangling", fd
.toPrettyChars());
754 return checkFunctionNeedsPlaceholder(fd
);
756 if (!adparent
&& !fd
.fbody
)
758 ignored("function %s because it is extern", fd
.toPrettyChars());
761 if (fd
.visibility
.kind
== AST
.Visibility
.Kind
.none || fd
.visibility
.kind
== AST
.Visibility
.Kind
.private_
)
763 ignored("function %s because it is private", fd
.toPrettyChars());
766 if (tf
&& !isSupportedType(tf
.next
))
768 ignored("function %s because its return type cannot be mapped to C++", fd
.toPrettyChars());
769 return checkFunctionNeedsPlaceholder(fd
);
771 if (tf
) foreach (i
, fparam
; tf
.parameterList
)
773 if (!isSupportedType(fparam
.type
))
775 ignored("function %s because one of its parameters has type `%s` which cannot be mapped to C++",
776 fd
.toPrettyChars(), fparam
.type
.toChars());
777 return checkFunctionNeedsPlaceholder(fd
);
781 writeProtection(fd
.visibility
.kind
);
783 if (tf
&& tf
.linkage
== LINK
.c
)
784 buf
.writestring("extern \"C\" ");
786 buf
.writestring("extern ");
787 if (adparent
&& fd
.isStatic())
788 buf
.writestring("static ");
789 else if (adparent
&& (
790 // Virtual functions in non-templated classes
791 (fd
.vtblIndex
!= -1 && !fd
.isOverride()) ||
793 // Virtual functions in templated classes (fd.vtblIndex still -1)
794 (tdparent
&& adparent
.isClassDeclaration() && !(this.storageClass
& AST
.STC
.final_ || fd
.isFinal
))))
795 buf
.writestring("virtual ");
797 debug (Debug_DtoH_Checks
)
798 if (adparent
&& !tdparent
)
800 auto s
= adparent
.search(Loc
.initial
, fd
.ident
);
801 auto cd
= adparent
.isClassDeclaration();
803 if (!(adparent
.storage_class
& AST
.STC
.abstract_
) &&
804 !(cd
&& cd
.isAbstract()) &&
805 s
is fd
&& !fd
.overnext
)
807 const cn
= adparent
.ident
.toChars();
808 const fn
= fd
.ident
.toChars();
809 const vi
= fd
.vtblIndex
;
811 checkbuf
.printf("assert(getSlotNumber <%s>(0, &%s::%s) == %d);",
817 if (adparent
&& fd
.isDisabled
&& global
.params
.cplusplus
< CppStdRevision
.cpp11
)
818 writeProtection(AST
.Visibility
.Kind
.private_
);
819 funcToBuffer(tf
, fd
);
822 if (tf
&& (tf
.isConst() || tf
.isImmutable()))
823 buf
.writestring(" const");
824 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
826 if (fd
.vtblIndex
!= -1 && !(adparent
.storage_class
& AST
.STC
.final_
) && fd
.isFinalFunc())
827 buf
.writestring(" final");
829 buf
.writestring(" override");
832 buf
.writestring(" = 0");
833 else if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
&& fd
.isDisabled())
834 buf
.writestring(" = delete");
836 buf
.writestringln(";");
837 if (adparent
&& fd
.isDisabled
&& global
.params
.cplusplus
< CppStdRevision
.cpp11
)
838 writeProtection(AST
.Visibility
.Kind
.public_
);
846 + Checks whether `fd` is a function that requires a dummy declaration
847 + instead of simply emitting the declaration (because it would cause
848 + ABI / behaviour issues). This includes:
850 + - virtual functions to ensure proper vtable layout
851 + - destructors that would break RAII
853 private void checkFunctionNeedsPlaceholder(AST
.FuncDeclaration fd
)
855 // Omit redundant declarations - the slot was already
856 // reserved in the base class
857 if (fd
.isVirtual() && fd
.isIntroducing())
859 // Hide placeholders because they are not ABI compatible
860 writeProtection(AST
.Visibility
.Kind
.private_
);
862 __gshared
int counter
; // Ensure unique names in all cases
863 buf
.printf("virtual void __vtable_slot_%u();", counter
++);
866 else if (fd
.isDtorDeclaration())
868 // Create inaccessible dtor to prevent code from keeping instances that
869 // need to be destroyed on the C++ side (but cannot call the dtor)
870 writeProtection(AST
.Visibility
.Kind
.private_
);
872 buf
.writestring(adparent
.ident
.toString());
873 buf
.writestringln("();");
877 override void visit(AST
.UnitTestDeclaration utd
)
879 debug (Debug_DtoH
) mixin(traceVisit
!utd
);
882 override void visit(AST
.VarDeclaration vd
)
884 debug (Debug_DtoH
) mixin(traceVisit
!vd
);
886 if (!shouldEmitAndMarkVisited(vd
))
889 // Tuple field are expanded into multiple VarDeclarations
890 // (we'll visit them later)
891 if (vd
.type
&& vd
.type
.isTypeTuple())
893 assert(vd
.aliasTuple
);
894 vd
.toAlias().accept(this);
898 if (vd
.originalType
&& vd
.type
== AST
.Type
.tsize_t
)
899 origType
= vd
.originalType
;
900 scope(exit
) origType
= null;
902 if (!vd
.alignment
.isDefault() && !vd
.alignment
.isUnknown())
904 buf
.printf("// Ignoring var %s alignment %d", vd
.toChars(), vd
.alignment
.get());
908 // Determine the variable type which might be missing inside of
909 // template declarations. Infer the type from the initializer then
910 AST
.Type type
= vd
.type
;
915 // Just a precaution, implicit type without initializer should be rejected
919 if (auto ei
= vd
._init
.isExpInitializer())
922 // Can happen if the expression needs further semantic
925 ignored("%s because the type could not be determined", vd
.toPrettyChars());
929 // Apply const/immutable to the inferred type
930 if (vd
.storage_class
& (AST
.STC
.const_ | AST
.STC
.immutable_
))
931 type
= type
.constOf();
934 if (vd
.storage_class
& AST
.STC
.manifest
)
936 EnumKind kind
= getEnumKind(type
);
938 if (vd
.visibility
.kind
== AST
.Visibility
.Kind
.none || vd
.visibility
.kind
== AST
.Visibility
.Kind
.private_
) {
939 ignored("enum `%s` because it is `%s`.", vd
.toPrettyChars(), AST
.visibilityToChars(vd
.visibility
.kind
));
943 writeProtection(vd
.visibility
.kind
);
947 case EnumKind
.Int
, EnumKind
.Numeric
:
948 // 'enum : type' is only available from C++-11 onwards.
949 if (global
.params
.cplusplus
< CppStdRevision
.cpp11
)
951 buf
.writestring("enum : ");
952 determineEnumType(type
).accept(this);
953 buf
.writestring(" { ");
954 writeIdentifier(vd
, true);
955 buf
.writestring(" = ");
956 auto ie
= AST
.initializerToExpression(vd
._init
).isIntegerExp();
957 visitInteger(ie
.toInteger(), type
);
958 buf
.writestring(" };");
961 case EnumKind
.String
, EnumKind
.Enum
:
962 buf
.writestring("static ");
963 auto target
= determineEnumType(type
);
965 buf
.writestring(" const ");
966 writeIdentifier(vd
, true);
967 buf
.writestring(" = ");
968 auto e
= AST
.initializerToExpression(vd
._init
);
969 printExpressionFor(target
, e
);
970 buf
.writestring(";");
974 ignored("enum `%s` because type `%s` is currently not supported for enum constants.", vd
.toPrettyChars(), type
.toChars());
982 if (vd
.storage_class
& (AST
.STC
.static_ | AST
.STC
.extern_ | AST
.STC
.gshared
) ||
983 vd
.parent
&& vd
.parent
.isModule())
985 const vdLinkage
= vd
.resolvedLinkage();
986 if (vdLinkage
!= LINK
.c
&& vdLinkage
!= LINK
.cpp
&& !(tdparent
&& (this.linkage
== LINK
.c ||
this.linkage
== LINK
.cpp
)))
988 ignored("variable %s because of linkage", vd
.toPrettyChars());
991 if (vd
.mangleOverride
&& vdLinkage
!= LINK
.c
)
993 ignored("variable %s because C++ doesn't support explicit mangling", vd
.toPrettyChars());
996 if (!isSupportedType(type
))
998 ignored("variable %s because its type cannot be mapped to C++", vd
.toPrettyChars());
1001 if (auto kc
= keywordClass(vd
.ident
))
1003 ignored("variable %s because its name is a %s", vd
.toPrettyChars(), kc
);
1006 writeProtection(vd
.visibility
.kind
);
1007 if (vdLinkage
== LINK
.c
)
1008 buf
.writestring("extern \"C\" ");
1010 buf
.writestring("extern ");
1012 buf
.writestring("static ");
1013 typeToBuffer(type
, vd
);
1020 writeProtection(vd
.visibility
.kind
);
1021 typeToBuffer(type
, vd
, true);
1022 buf
.writestringln(";");
1024 debug (Debug_DtoH_Checks
)
1027 const pn
= adparent
.ident
.toChars();
1028 const vn
= vd
.ident
.toChars();
1029 const vo
= vd
.offset
;
1030 checkbuf
.printf("assert(offsetof(%s, %s) == %d);",
1038 visit(cast(AST
.Dsymbol
)vd
);
1041 override void visit(AST
.TypeInfoDeclaration tid
)
1043 debug (Debug_DtoH
) mixin(traceVisit
!tid
);
1046 override void visit(AST
.AliasDeclaration ad
)
1048 debug (Debug_DtoH
) mixin(traceVisit
!ad
);
1050 // Declared in object.d but already included in `#include`s
1051 if (ad
.ident
== Id
._size_t || ad
.ident
== Id
._ptrdiff_t
)
1054 if (!shouldEmitAndMarkVisited(ad
))
1057 writeProtection(ad
.visibility
.kind
);
1059 if (auto t
= ad
.type
)
1061 if (t
.ty
== AST
.Tdelegate || t
.ty
== AST
.Tident
)
1063 visit(cast(AST
.Dsymbol
)ad
);
1067 // for function pointers we need to original type
1068 if (ad
.originalType
&& ad
.type
.ty
== AST
.Tpointer
&&
1069 (cast(AST
.TypePointer
)t
).nextOf
.ty
== AST
.Tfunction
)
1071 origType
= ad
.originalType
;
1073 scope(exit
) origType
= null;
1075 buf
.writestring("typedef ");
1076 typeToBuffer(origType
!is null ? origType
: t
, ad
);
1084 if (auto ti
= ad
.aliassym
.isTemplateInstance())
1089 if (auto sd
= ad
.aliassym
.isStructDeclaration())
1091 buf
.writestring("typedef ");
1092 sd
.type
.accept(this);
1093 buf
.writestring(" ");
1094 writeIdentifier(ad
);
1098 else if (auto td
= ad
.aliassym
.isTemplateDeclaration())
1100 if (global
.params
.cplusplus
< CppStdRevision
.cpp11
)
1102 ignored("%s because `using` declarations require C++ 11", ad
.toPrettyChars());
1106 printTemplateParams(td
);
1107 buf
.writestring("using ");
1108 writeIdentifier(ad
);
1109 buf
.writestring(" = ");
1113 foreach (const idx
, const p
; *td
.parameters
)
1116 buf
.writestring(", ");
1117 writeIdentifier(p
.ident
, p
.loc
, "parameter", true);
1119 buf
.writestringln(">;");
1123 auto fd
= ad
.aliassym
.isFuncDeclaration();
1125 if (fd
&& (fd
.isGenerated() || fd
.isDtorDeclaration()))
1127 // Ignore. It's taken care of while visiting FuncDeclaration
1131 // Recognize member function aliases, e.g. alias visit = Parent.visit;
1134 auto pd
= fd
.isMember();
1137 ignored("%s because free functions cannot be aliased in C++", ad
.toPrettyChars());
1139 else if (global
.params
.cplusplus
< CppStdRevision
.cpp11
)
1141 ignored("%s because `using` declarations require C++ 11", ad
.toPrettyChars());
1143 else if (ad
.ident
!= fd
.ident
)
1145 ignored("%s because `using` cannot rename functions in aggregates", ad
.toPrettyChars());
1147 else if (fd
.toAliasFunc().parent
.isTemplateMixin())
1149 // Member's of template mixins are directly emitted into the aggregate
1153 buf
.writestring("using ");
1155 // Print prefix of the base class if this function originates from a superclass
1156 // because alias might be resolved through multiple classes, e.g.
1157 // e.g. for alias visit = typeof(super).visit in the visitors
1158 if (!fd
.isIntroducing())
1159 printPrefix(ad
.toParent().isClassDeclaration().baseClass
);
1163 buf
.writestring(fd
.ident
.toChars());
1164 buf
.writestringln(";");
1169 ignored("%s %s", ad
.aliassym
.kind(), ad
.aliassym
.toPrettyChars());
1172 override void visit(AST
.Nspace ns
)
1174 debug (Debug_DtoH
) mixin(traceVisit
!ns
);
1175 handleNspace(ns
, ns
.members
);
1178 override void visit(AST
.CPPNamespaceDeclaration ns
)
1180 debug (Debug_DtoH
) mixin(traceVisit
!ns
);
1181 handleNspace(ns
, ns
.decl
);
1184 /// Writes the namespace declaration and visits all members
1185 private void handleNspace(AST
.Dsymbol namespace
, Dsymbols
* members
)
1187 buf
.writestring("namespace ");
1188 writeIdentifier(namespace
);
1190 buf
.writestring("{");
1193 foreach(decl
;(*members
))
1198 buf
.writestring("}");
1202 override void visit(AST
.AnonDeclaration ad
)
1204 debug (Debug_DtoH
) mixin(traceVisit
!ad
);
1206 const anonStash
= inAnonymousDecl
;
1207 inAnonymousDecl
= true;
1208 scope (exit
) inAnonymousDecl
= anonStash
;
1210 buf
.writestringln(ad
.isunion ?
"union" : "struct");
1211 buf
.writestringln("{");
1213 foreach (s
; *ad
.decl
)
1218 buf
.writestringln("};");
1221 private bool memberField(AST
.VarDeclaration vd
) @safe
1223 if (!vd
.type ||
!vd
.type
.deco ||
!vd
.ident
)
1227 if (vd
.type
.ty
== AST
.Tfunction
)
1229 if (vd
.type
.ty
== AST
.Tsarray
)
1234 override void visit(AST
.StructDeclaration sd
)
1236 debug (Debug_DtoH
) mixin(traceVisit
!sd
);
1238 if (!shouldEmitAndMarkVisited(sd
))
1241 const ignoredStash
= this.ignoredCounter
;
1242 scope (exit
) this.ignoredCounter
= ignoredStash
;
1244 pushAlignToBuffer(sd
.alignment
);
1246 writeProtection(sd
.visibility
.kind
);
1248 const structAsClass
= sd
.cppmangle
== CPPMANGLE
.asClass
;
1249 if (sd
.isUnionDeclaration())
1250 buf
.writestring("union ");
1252 buf
.writestring(structAsClass ?
"class " : "struct ");
1254 writeIdentifier(sd
);
1257 buf
.writestringln(";");
1262 // D structs are always final
1263 if (!sd
.isUnionDeclaration())
1264 buf
.writestring(" final");
1267 buf
.writestring("{");
1269 const protStash
= this.currentVisibility
;
1270 this.currentVisibility
= structAsClass ? AST
.Visibility
.Kind
.private_
: AST
.Visibility
.Kind
.public_
;
1271 scope (exit
) this.currentVisibility
= protStash
;
1275 auto save
= adparent
;
1278 foreach (m
; *sd
.members
)
1282 // Generate default ctor
1283 if (!sd
.noDefaultCtor
&& !sd
.isUnionDeclaration())
1285 writeProtection(AST
.Visibility
.Kind
.public_
);
1286 buf
.printf("%s()", sd
.ident
.toChars());
1290 foreach (vd
; sd
.fields
)
1292 if (!memberField(vd
) || vd
.overlapped
)
1296 if (!vd
._init
&& !vd
.type
.isTypeBasic() && !vd
.type
.isTypePointer
&& !vd
.type
.isTypeStruct
&&
1297 !vd
.type
.isTypeClass
&& !vd
.type
.isTypeDArray
&& !vd
.type
.isTypeSArray
)
1301 if (vd
._init
&& vd
._init
.isVoidInitializer())
1306 buf
.writestringln(" :");
1311 buf
.writestringln(",");
1313 writeIdentifier(vd
, true);
1318 auto e
= AST
.initializerToExpression(vd
._init
);
1319 printExpressionFor(vd
.type
, e
, true);
1325 buf
.writestringln("{");
1326 buf
.writestringln("}");
1327 auto ctor
= sd
.ctor ? sd
.ctor
.isFuncDeclaration() : null;
1328 if (varCount
&& (!ctor || ctor
.storage_class
& AST
.STC
.disable
))
1330 buf
.printf("%s(", sd
.ident
.toChars());
1332 foreach (vd
; sd
.fields
)
1334 if (!memberField(vd
) || vd
.overlapped
)
1337 buf
.writestring(", ");
1340 typeToBuffer(vd
.type
, vd
, true);
1341 // Don't print default value for first parameter to not clash
1342 // with the default ctor defined above
1345 buf
.writestring(" = ");
1346 printExpressionFor(vd
.type
, findDefaultInitializer(vd
));
1350 buf
.writestring(") :");
1355 foreach (vd
; sd
.fields
)
1357 if (!memberField(vd
) || vd
.overlapped
)
1363 buf
.writestringln(",");
1365 writeIdentifier(vd
, true);
1367 writeIdentifier(vd
, true);
1371 buf
.writestringln("{}");
1378 buf
.writestringln("};");
1380 popAlignToBuffer(sd
.alignment
);
1383 // Workaround because size triggers a forward-reference error
1384 // for struct templates (the size is undetermined even if the
1385 // size doesn't depend on the parameters)
1386 debug (Debug_DtoH_Checks
)
1390 const sn
= sd
.ident
.toChars();
1391 const sz
= sd
.size(Loc
.initial
);
1392 checkbuf
.printf("assert(sizeof(%s) == %llu);", sn
, sz
);
1398 /// Starts a custom alignment section using `#pragma pack` if
1399 /// `alignment` specifies a custom alignment
1400 private void pushAlignToBuffer(structalign_t alignment
)
1402 // DMD ensures alignment is a power of two
1403 //assert(alignment > 0 && ((alignment & (alignment - 1)) == 0),
1404 // "Invalid alignment size");
1406 // When no alignment is specified, `uint.max` is the default
1407 // FIXME: alignment is 0 for structs templated members
1408 if (alignment
.isDefault() ||
(tdparent
&& alignment
.isUnknown()))
1413 buf
.printf("#pragma pack(push, %d)", alignment
.get());
1417 /// Ends a custom alignment section using `#pragma pack` if
1418 /// `alignment` specifies a custom alignment
1419 private void popAlignToBuffer(structalign_t alignment
) @safe
1421 if (alignment
.isDefault() ||
(tdparent
&& alignment
.isUnknown()))
1424 buf
.writestringln("#pragma pack(pop)");
1427 override void visit(AST
.ClassDeclaration cd
)
1429 debug (Debug_DtoH
) mixin(traceVisit
!cd
);
1431 if (cd
.baseClass
&& shouldEmit(cd
))
1432 includeSymbol(cd
.baseClass
);
1434 if (!shouldEmitAndMarkVisited(cd
))
1437 writeProtection(cd
.visibility
.kind
);
1439 const classAsStruct
= cd
.cppmangle
== CPPMANGLE
.asStruct
;
1440 buf
.writestring(classAsStruct ?
"struct " : "class ");
1441 writeIdentifier(cd
);
1443 if (cd
.storage_class
& AST
.STC
.final_ ||
(tdparent
&& this.storageClass
& AST
.STC
.final_
))
1444 buf
.writestring(" final");
1446 assert(cd
.baseclasses
);
1448 foreach (i
, base
; *cd
.baseclasses
)
1450 buf
.writestring(i
== 0 ?
" : public " : ", public ");
1452 // Base classes/interfaces might depend on template parameters,
1453 // e.g. class A(T) : B!T { ... }
1454 if (base
.sym
is null)
1456 base
.type
.accept(this);
1460 writeFullName(base
.sym
);
1466 buf
.writestring(";");
1473 buf
.writestringln("{");
1475 const protStash
= this.currentVisibility
;
1476 this.currentVisibility
= classAsStruct ? AST
.Visibility
.Kind
.public_
: AST
.Visibility
.Kind
.private_
;
1477 scope (exit
) this.currentVisibility
= protStash
;
1479 auto save
= adparent
;
1482 foreach (m
; *cd
.members
)
1489 buf
.writestringln("};");
1493 override void visit(AST
.EnumDeclaration ed
)
1495 debug (Debug_DtoH
) mixin(traceVisit
!ed
);
1497 if (!shouldEmitAndMarkVisited(ed
))
1502 //ignored("%s because it is a special C++ type", ed.toPrettyChars());
1506 // we need to know a bunch of stuff about the enum...
1507 bool isAnonymous
= ed
.ident
is null;
1508 const isOpaque
= !ed
.members
;
1509 AST
.Type type
= ed
.memtype
;
1510 if (!type
&& !isOpaque
)
1512 // check all keys have matching type
1513 foreach (_m
; *ed
.members
)
1515 auto m
= _m
.isEnumMember();
1518 else if (m
.type
!is type
)
1525 EnumKind kind
= getEnumKind(type
);
1529 // Opaque enums were introduced in C++ 11 (workaround?)
1530 if (global
.params
.cplusplus
< CppStdRevision
.cpp11
)
1532 ignored("%s because opaque enums require C++ 11", ed
.toPrettyChars());
1535 // Opaque enum defaults to int but the type might not be set
1538 kind
= EnumKind
.Int
;
1540 // Cannot apply namespace workaround for non-integral types
1541 else if (kind
!= EnumKind
.Int
&& kind
!= EnumKind
.Numeric
)
1543 ignored("enum %s because of its base type", ed
.toPrettyChars());
1548 // determine if this is an enum, or just a group of manifest constants
1549 bool manifestConstants
= !isOpaque
&& (!type ||
(isAnonymous
&& kind
== EnumKind
.Other
));
1550 assert(!manifestConstants || isAnonymous
);
1552 writeProtection(ed
.visibility
.kind
);
1554 // write the enum header
1555 if (!manifestConstants
)
1557 if (kind
== EnumKind
.Int || kind
== EnumKind
.Numeric
)
1559 buf
.writestring("enum");
1560 // D enums are strong enums, but there exists only a direct mapping
1561 // with 'enum class' from C++-11 onwards.
1562 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
1566 buf
.writestring(" class ");
1567 writeIdentifier(ed
);
1569 if (kind
== EnumKind
.Numeric
)
1571 buf
.writestring(" : ");
1572 determineEnumType(type
).accept(this);
1575 else if (!isAnonymous
)
1578 writeIdentifier(ed
);
1583 buf
.writestring("namespace");
1587 writeIdentifier(ed
);
1590 // Opaque enums have no members, hence skip the body
1593 buf
.writestringln(";");
1599 buf
.writestringln("{");
1603 // emit constant for each member
1604 if (!manifestConstants
)
1607 foreach (_m
; *ed
.members
)
1609 auto m
= _m
.isEnumMember();
1610 AST
.Type memberType
= type ? type
: m
.type
;
1611 const EnumKind memberKind
= type ? kind
: getEnumKind(memberType
);
1613 if (!manifestConstants
&& (kind
== EnumKind
.Int || kind
== EnumKind
.Numeric
))
1615 // C++-98 compatible enums must use the typename as a prefix to avoid
1616 // collisions with other identifiers in scope. For consistency with D,
1617 // the enum member `Type.member` is emitted as `Type_member` in C++-98.
1618 if (!isAnonymous
&& global
.params
.cplusplus
< CppStdRevision
.cpp11
)
1620 writeIdentifier(ed
);
1623 writeIdentifier(m
, true);
1624 buf
.writestring(" = ");
1626 auto ie
= cast(AST
.IntegerExp
)m
.value
;
1627 visitInteger(ie
.toInteger(), memberType
);
1628 buf
.writestring(",");
1630 else if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
&&
1631 manifestConstants
&& (memberKind
== EnumKind
.Int || memberKind
== EnumKind
.Numeric
))
1633 buf
.writestring("enum : ");
1634 determineEnumType(memberType
).accept(this);
1635 buf
.writestring(" { ");
1636 writeIdentifier(m
, true);
1637 buf
.writestring(" = ");
1639 auto ie
= cast(AST
.IntegerExp
)m
.value
;
1640 visitInteger(ie
.toInteger(), memberType
);
1641 buf
.writestring(" };");
1645 buf
.writestring("static ");
1646 auto target
= determineEnumType(memberType
);
1647 target
.accept(this);
1648 buf
.writestring(" const ");
1649 writeIdentifier(m
, true);
1650 buf
.writestring(" = ");
1651 printExpressionFor(target
, m
.origValue
);
1652 buf
.writestring(";");
1657 if (!manifestConstants
)
1659 // write the enum tail
1660 if (!manifestConstants
)
1661 buf
.writestring("};");
1666 override void visit(AST
.EnumMember em
)
1670 // Members of anonymous members are reachable without referencing the
1671 // EnumDeclaration, e.g. public import foo : someEnumMember;
1672 if (em
.ed
.isAnonymous())
1678 assert(false, "This node type should be handled in the EnumDeclaration");
1681 override void visit(AST
.TupleDeclaration tup
)
1683 debug (Debug_DtoH
) mixin(traceVisit
!tup
);
1685 tup
.foreachVar((s
) { s
.accept(this); });
1689 * Prints a member/parameter/variable declaration into `buf`.
1692 * t = the type (used if `this.origType` is null)
1693 * s = the symbol denoting the identifier
1694 * canFixup = whether the identifier may be changed without affecting
1695 * binary compatibility (forwarded to `writeIdentifier`)
1697 private void typeToBuffer(AST
.Type t
, AST
.Dsymbol s
, const bool canFixup
= false)
1701 printf("[typeToBuffer(AST.Type, AST.Dsymbol) enter] %s sym %s\n", t
.toChars(), s
.toChars());
1702 scope(exit
) printf("[typeToBuffer(AST.Type, AST.Dsymbol) exit] %s sym %s\n", t
.toChars(), s
.toChars());
1705 // The context pointer (represented as `ThisDeclaration`) is named
1706 // `this` but accessible via `outer`
1707 if (auto td
= s
.isThisDeclaration())
1710 this.ident
= Id
.outer
;
1713 this.ident
= s
.ident
;
1715 auto type
= origType
!is null ? origType
: t
;
1716 AST
.Dsymbol customLength
;
1718 // Check for quirks that are usually resolved during semantic
1721 // Declarations within template declarations might use TypeAArray
1722 // instead of TypeSArray when the length is not an IntegerExp,
1723 // e.g. int[SOME_CONSTANT]
1724 if (auto taa
= type
.isTypeAArray())
1726 // Try to resolve the symbol from the key if it's not an actual type
1728 if (auto ti
= taa
.index
.isTypeIdentifier())
1733 auto sym
= findSymbol(id
, adparent ? adparent
: tdparent
);
1736 // Couldn't resolve, assume actual AA
1738 else if (AST
.isType(sym
))
1740 // a real associative array, forward to visit
1742 else if (auto vd
= sym
.isVarDeclaration())
1744 // Actually a static array with length symbol
1746 type
= taa
.next
; // visit the element type, length is written below
1750 printf("Resolved unexpected symbol while determining static array length: %s\n", sym
.toChars());
1761 // Custom identifier doesn't need further checks
1762 if (this.ident
!is s
.ident
)
1763 buf
.writestring(this.ident
.toString());
1765 writeIdentifier(s
, canFixup
);
1770 // Size is either taken from the type or resolved above
1771 auto tsa
= t
.isTypeSArray();
1772 if (tsa || customLength
)
1776 tsa
.dim
.accept(this);
1778 writeFullName(customLength
);
1781 else if (t
.isTypeNoreturn())
1782 buf
.writestring("[0]");
1785 override void visit(AST
.Type t
)
1787 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1788 printf("Invalid type: %s\n", t
.toPrettyChars());
1792 override void visit(AST
.TypeNoreturn t
)
1794 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1796 buf
.writestring("/* noreturn */ char");
1799 override void visit(AST
.TypeIdentifier t
)
1801 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1803 // Try to resolve the referenced symbol
1804 if (auto sym
= findSymbol(t
.ident
))
1805 ensureDeclared(outermostSymbol(sym
));
1807 if (t
.idents
.length
)
1808 buf
.writestring("typename ");
1810 writeIdentifier(t
.ident
, t
.loc
, "type", tdparent
!is null);
1812 foreach (arg
; t
.idents
)
1814 buf
.writestring("::");
1816 import dmd
.root
.rootobject
;
1817 // Is this even possible?
1818 if (arg
.dyncast
!= DYNCAST
.identifier
)
1820 printf("arg.dyncast() = %d\n", arg
.dyncast());
1823 buf
.writestring((cast(Identifier
) arg
).toChars());
1827 override void visit(AST
.TypeNull t
)
1829 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1831 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
1832 buf
.writestring("nullptr_t");
1834 buf
.writestring("void*");
1838 override void visit(AST
.TypeTypeof t
)
1840 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1846 t
.exp
.type
.accept(this);
1848 else if (t
.exp
.isThisExp())
1850 // Short circuit typeof(this) => <Aggregate name>
1852 buf
.writestring(adparent
.ident
.toChars());
1856 // Relying on C++'s typeof might produce wrong results
1857 // but it's the best we've got here.
1858 buf
.writestring("typeof(");
1864 override void visit(AST
.TypeBasic t
)
1866 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1868 if (t
.isConst() || t
.isImmutable())
1869 buf
.writestring("const ");
1873 case AST
.Tvoid
: typeName
= "void"; break;
1874 case AST
.Tbool
: typeName
= "bool"; break;
1875 case AST
.Tchar
: typeName
= "char"; break;
1876 case AST
.Twchar
: typeName
= "char16_t"; break;
1877 case AST
.Tdchar
: typeName
= "char32_t"; break;
1878 case AST
.Tint8
: typeName
= "int8_t"; break;
1879 case AST
.Tuns8
: typeName
= "uint8_t"; break;
1880 case AST
.Tint16
: typeName
= "int16_t"; break;
1881 case AST
.Tuns16
: typeName
= "uint16_t"; break;
1882 case AST
.Tint32
: typeName
= "int32_t"; break;
1883 case AST
.Tuns32
: typeName
= "uint32_t"; break;
1884 case AST
.Tint64
: typeName
= "int64_t"; break;
1885 case AST
.Tuns64
: typeName
= "uint64_t"; break;
1886 case AST
.Tfloat32
: typeName
= "float"; break;
1887 case AST
.Tfloat64
: typeName
= "double"; break;
1889 typeName
= "_d_real";
1892 case AST
.Tcomplex32
: typeName
= "_Complex float"; break;
1893 case AST
.Tcomplex64
: typeName
= "_Complex double"; break;
1894 case AST
.Tcomplex80
:
1895 typeName
= "_Complex _d_real";
1898 // ???: This is not strictly correct, but it should be ignored
1899 // in all places where it matters most (variables, functions, ...).
1900 case AST
.Timaginary32
: typeName
= "float"; break;
1901 case AST
.Timaginary64
: typeName
= "double"; break;
1902 case AST
.Timaginary80
:
1903 typeName
= "_d_real";
1910 buf
.writestring(typeName
);
1913 override void visit(AST
.TypePointer t
)
1915 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1917 auto ts
= t
.next
.isTypeStruct();
1918 if (ts
&& !strcmp(ts
.sym
.ident
.toChars(), "__va_list_tag"))
1920 buf
.writestring("va_list");
1924 // Pointer targets can be forward referenced
1925 const fwdSave
= forwarding
;
1927 scope (exit
) forwarding
= fwdSave
;
1929 t
.next
.accept(this);
1930 if (t
.next
.ty
!= AST
.Tfunction
)
1932 if (t
.isConst() || t
.isImmutable())
1933 buf
.writestring(" const");
1936 override void visit(AST
.TypeSArray t
)
1938 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1939 t
.next
.accept(this);
1942 override void visit(AST
.TypeAArray t
)
1944 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1945 AST
.Type
.tvoidptr
.accept(this);
1948 override void visit(AST
.TypeFunction tf
)
1950 debug (Debug_DtoH
) mixin(traceVisit
!tf
);
1952 tf
.next
.accept(this);
1956 buf
.writestring(ident
.toChars());
1960 foreach (i
, fparam
; tf
.parameterList
)
1963 buf
.writestring(", ");
1964 fparam
.accept(this);
1966 if (tf
.parameterList
.varargs
)
1968 if (tf
.parameterList
.parameters
.length
&& tf
.parameterList
.varargs
== 1)
1969 buf
.writestring(", ");
1970 buf
.writestring("...");
1975 /// Writes the type that represents `ed` into `buf`.
1976 /// (Might not be `ed` for special enums or enums that were emitted as namespaces)
1977 private void enumToBuffer(AST
.EnumDeclaration ed
)
1979 debug (Debug_DtoH
) mixin(traceVisit
!ed
);
1983 if (ed
.ident
== DMDType
.c_long
)
1984 buf
.writestring("long");
1985 else if (ed
.ident
== DMDType
.c_ulong
)
1986 buf
.writestring("unsigned long");
1987 else if (ed
.ident
== DMDType
.c_longlong
)
1988 buf
.writestring("long long");
1989 else if (ed
.ident
== DMDType
.c_ulonglong
)
1990 buf
.writestring("unsigned long long");
1991 else if (ed
.ident
== DMDType
.c_long_double
)
1992 buf
.writestring("long double");
1993 else if (ed
.ident
== DMDType
.c_char
)
1994 buf
.writestring("char");
1995 else if (ed
.ident
== DMDType
.c_wchar_t
)
1996 buf
.writestring("wchar_t");
1997 else if (ed
.ident
== DMDType
.c_complex_float
)
1998 buf
.writestring("_Complex float");
1999 else if (ed
.ident
== DMDType
.c_complex_double
)
2000 buf
.writestring("_Complex double");
2001 else if (ed
.ident
== DMDType
.c_complex_real
)
2002 buf
.writestring("_Complex long double");
2011 const kind
= getEnumKind(ed
.memtype
);
2013 // Check if the enum was emitted as a real enum
2014 if (kind
== EnumKind
.Int || kind
== EnumKind
.Numeric
)
2020 // Use the base type if the enum was emitted as a namespace
2021 buf
.printf("/* %s */ ", ed
.ident
.toChars());
2022 ed
.memtype
.accept(this);
2026 override void visit(AST
.TypeEnum t
)
2028 debug (Debug_DtoH
) mixin(traceVisit
!t
);
2030 if (t
.isConst() || t
.isImmutable())
2031 buf
.writestring("const ");
2032 enumToBuffer(t
.sym
);
2035 override void visit(AST
.TypeStruct t
)
2037 debug (Debug_DtoH
) mixin(traceVisit
!t
);
2039 if (t
.isConst() || t
.isImmutable())
2040 buf
.writestring("const ");
2041 writeFullName(t
.sym
);
2044 override void visit(AST
.TypeDArray t
)
2046 debug (Debug_DtoH
) mixin(traceVisit
!t
);
2048 if (t
.isConst() || t
.isImmutable())
2049 buf
.writestring("const ");
2050 buf
.writestring("_d_dynamicArray< ");
2051 t
.next
.accept(this);
2052 buf
.writestring(" >");
2055 override void visit(AST
.TypeInstance t
)
2057 visitTi(t
.tempinst
);
2060 private void visitTi(AST
.TemplateInstance ti
)
2062 debug (Debug_DtoH
) mixin(traceVisit
!ti
);
2064 // Ensure that the TD appears before the instance
2065 if (auto td
= findTemplateDeclaration(ti
))
2068 foreach (o
; *ti
.tiargs
)
2073 buf
.writestring(ti
.name
.toChars());
2075 foreach (i
, o
; *ti
.tiargs
)
2078 buf
.writestring(", ");
2079 if (auto tt
= AST
.isType(o
))
2090 buf
.writestring(" >");
2093 override void visit(AST
.TemplateDeclaration td
)
2095 debug (Debug_DtoH
) mixin(traceVisit
!td
);
2097 if (!shouldEmitAndMarkVisited(td
))
2100 if (!td
.parameters ||
!td
.onemember ||
(!td
.onemember
.isStructDeclaration
&& !td
.onemember
.isClassDeclaration
&& !td
.onemember
.isFuncDeclaration
))
2102 visit(cast(AST
.Dsymbol
)td
);
2106 // Explicitly disallow templates with non-type parameters or specialization.
2107 foreach (p
; *td
.parameters
)
2109 if (!p
.isTemplateTypeParameter() || p
.specialization())
2111 visit(cast(AST
.Dsymbol
)td
);
2116 auto save
= tdparent
;
2118 const bookmark
= buf
.length
;
2119 printTemplateParams(td
);
2121 const oldIgnored
= this.ignoredCounter
;
2122 td
.onemember
.accept(this);
2124 // Remove "template<...>" if the symbol could not be emitted
2125 if (oldIgnored
!= this.ignoredCounter
)
2126 buf
.setsize(bookmark
);
2131 /// Writes the template<...> header for the supplied template declaration
2132 private void printTemplateParams(const AST
.TemplateDeclaration td
)
2134 buf
.writestring("template <");
2136 foreach (p
; *td
.parameters
)
2141 buf
.writestring(", ");
2142 buf
.writestring("typename ");
2143 writeIdentifier(p
.ident
, p
.loc
, "template parameter", true);
2145 buf
.writestringln(">");
2148 /// Emit declarations of the TemplateMixin in the current scope
2149 override void visit(AST
.TemplateMixin tm
)
2151 debug (Debug_DtoH
) mixin(traceVisit
!tm
);
2153 auto members
= tm
.members
;
2155 // members are missing for instances inside of TemplateDeclarations, e.g.
2156 // template Foo(T) { mixin Bar!T; }
2159 if (auto td
= findTemplateDeclaration(tm
))
2160 members
= td
.members
; // Emit members of the template
2162 return; // Cannot emit mixin
2165 foreach (s
; *members
)
2167 // kind is undefined without semantic
2168 const kind
= s
.visible().kind
;
2169 if (kind
== AST
.Visibility
.Kind
.public_ || kind
== AST
.Visibility
.Kind
.undefined
)
2175 * Finds a symbol with the identifier `name` by iterating the linked list of parent
2176 * symbols, starting from `context`.
2178 * Returns: the symbol or `null` if missing
2180 private AST
.Dsymbol
findSymbol(Identifier name
, AST
.Dsymbol context
)
2182 // Follow the declaration context
2183 for (auto par
= context
; par
; par
= par
.toParentDecl())
2185 // Check that `name` doesn't refer to a template parameter
2186 if (auto td
= par
.isTemplateDeclaration())
2188 foreach (const p
; *td
.parameters
)
2190 if (p
.ident
== name
)
2195 if (auto mem
= findMember(par
, name
))
2204 private AST
.Dsymbol
findSymbol(Identifier name
)
2208 sym
= findSymbol(name
, adparent
);
2210 if (!sym
&& tdparent
)
2211 sym
= findSymbol(name
, tdparent
);
2216 /// Finds the template declaration for instance `ti`
2217 private AST
.TemplateDeclaration
findTemplateDeclaration(AST
.TemplateInstance ti
)
2220 return ti
.tempdecl
.isTemplateDeclaration();
2222 assert(tdparent
); // Only missing inside of templates
2224 // Search for the TemplateDeclaration, starting from the enclosing scope
2225 // if known or the enclosing template.
2226 auto sym
= findSymbol(ti
.name
, ti
.parent ? ti
.parent
: tdparent
);
2227 return sym ? sym
.isTemplateDeclaration() : null;
2230 override void visit(AST
.TypeClass t
)
2232 debug (Debug_DtoH
) mixin(traceVisit
!t
);
2234 // Classes are emitted as pointer and hence can be forwarded
2235 const fwdSave
= forwarding
;
2237 scope (exit
) forwarding
= fwdSave
;
2239 if (t
.isConst() || t
.isImmutable())
2240 buf
.writestring("const ");
2241 writeFullName(t
.sym
);
2243 if (t
.isConst() || t
.isImmutable())
2244 buf
.writestring(" const");
2248 * Writes the function signature to `buf`.
2251 * fd = the function to print
2254 private void funcToBuffer(AST
.TypeFunction tf
, AST
.FuncDeclaration fd
)
2258 printf("[funcToBuffer(AST.TypeFunction) enter] %s\n", fd
.toChars());
2259 scope(exit
) printf("[funcToBuffer(AST.TypeFunction) exit] %s\n", fd
.toChars());
2262 auto originalType
= cast(AST
.TypeFunction
)fd
.originalType
;
2264 if (fd
.isCtorDeclaration() || fd
.isDtorDeclaration())
2266 if (fd
.isDtorDeclaration())
2270 buf
.writestring(adparent
.toChars());
2273 assert(fd
.isDtorDeclaration());
2274 buf
.writestring("()");
2280 import dmd
.root
.string
: toDString
;
2281 assert(tf
.next
, fd
.loc
.toChars().toDString());
2283 tf
.next
== AST
.Type
.tsize_t ? originalType
.next
.accept(this) : tf
.next
.accept(this);
2287 writeIdentifier(fd
);
2291 foreach (i
, fparam
; tf
.parameterList
)
2294 buf
.writestring(", ");
2295 if (fparam
.type
== AST
.Type
.tsize_t
&& originalType
)
2297 fparam
= originalType
.parameterList
[i
];
2299 fparam
.accept(this);
2301 if (tf
.parameterList
.varargs
)
2303 if (tf
.parameterList
.parameters
.length
&& tf
.parameterList
.varargs
== 1)
2304 buf
.writestring(", ");
2305 buf
.writestring("...");
2310 override void visit(AST
.Parameter p
)
2312 debug (Debug_DtoH
) mixin(traceVisit
!p
);
2317 // Reference parameters can be forwarded
2318 const fwdStash
= this.forwarding
;
2319 this.forwarding
= !!(p
.storageClass
& AST
.STC
.ref_
);
2320 p
.type
.accept(this);
2321 this.forwarding
= fwdStash
;
2324 if (p
.storageClass
& (AST
.STC
.ref_ | AST
.STC
.out_
))
2328 // FIXME: Parameter is missing a Loc
2329 writeIdentifier(ident
, Loc
.initial
, "parameter", true);
2334 //printf("%s %d\n", p.defaultArg.toChars, p.defaultArg.op);
2335 buf
.writestring(" = ");
2336 // Always emit the FDN of a symbol for the default argument,
2337 // to avoid generating an ambiguous assignment.
2338 auto save
= adparent
;
2340 printExpressionFor(p
.type
, p
.defaultArg
);
2346 * Prints `exp` as an expression of type `target` while inserting
2347 * appropriate code when implicit conversion does not translate
2348 * directly to C++, e.g. from an enum to its base type.
2351 * target = the type `exp` is converted to
2352 * exp = the expression to print
2353 * isCtor = if `exp` is a ctor argument
2355 private void printExpressionFor(AST
.Type target
, AST
.Expression exp
, const bool isCtor
= false)
2357 /// Determines if a static_cast is required
2358 static bool needsCast(AST
.Type target
, AST
.Expression exp
)
2360 // import std.stdio;
2361 // writefln("%s:%s: target = %s, type = %s (%s)", exp.loc.linnum, exp.loc.charnum, target, exp.type, exp.op);
2363 auto source
= exp
.type
;
2365 // DotVarExp resolve conversions, e.g from an enum to its base type
2366 if (auto dve
= exp
.isDotVarExp())
2367 source
= dve
.var
.type
;
2370 // Defensively assume that the cast is required
2373 // Conversions from enum class to base type require static_cast
2374 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
&&
2375 source
.isTypeEnum
&& !target
.isTypeEnum
)
2381 // Slices are emitted as a special struct, hence we need to fix up
2382 // any expression initialising a slice variable/member
2383 if (auto ta
= target
.isTypeDArray())
2385 if (exp
.isNullExp())
2389 // Don't emit, use default ctor
2391 else if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
2393 // Prefer initializer list
2394 buf
.writestring("{}");
2398 // Write __d_dynamic_array<TYPE>()
2400 buf
.writestring("()");
2405 if (auto se
= exp
.isStringExp())
2407 // Rewrite as <length> + <literal> pair optionally
2408 // wrapped in a initializer list/ctor call
2410 const initList
= global
.params
.cplusplus
>= CppStdRevision
.cpp11
;
2414 buf
.writestring("{ ");
2418 buf
.writestring("( ");
2422 buf
.printf("%zu, ", se
.len
);
2426 buf
.writestring(initList ?
" }" : " )");
2431 else if (auto ce
= exp
.isCastExp())
2436 else if (ce
.e1
.type
)
2437 // Try the expression type with modifiers in case of cast(const) in templates
2438 ce
.e1
.type
.castMod(ce
.mod
).accept(this);
2440 // Fallback, not necessarily correct but the best we've got here
2441 target
.accept(this);
2442 buf
.writestring(") ");
2445 else if (needsCast(target
, exp
))
2447 buf
.writestring("static_cast<");
2448 target
.accept(this);
2449 buf
.writestring(">(");
2459 override void visit(AST
.Expression e
)
2461 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2463 // Valid in most cases, others should be overridden below
2464 // to use the appropriate operators (:: and ->)
2465 buf
.writestring(e
.toString());
2468 override void visit(AST
.UnaExp e
)
2470 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2472 buf
.writestring(expToString(e
.op
));
2476 override void visit(AST
.BinExp e
)
2478 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2482 buf
.writestring(expToString(e
.op
));
2487 /// Translates operator `op` into the C++ representation
2488 private extern(D
) static string
expToString(const EXP op
)
2490 switch (op
) with (EXP
)
2492 case identity
: return "==";
2493 case notIdentity
: return "!=";
2495 return EXPtoString(op
);
2499 override void visit(AST
.VarExp e
)
2501 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2503 // Local members don't need another prefix and might've been renamed
2506 includeSymbol(e
.var
);
2507 writeIdentifier(e
.var
, true);
2510 writeFullName(e
.var
);
2513 /// Partially prints the FQN including parent aggregates
2514 private void printPrefix(AST
.Dsymbol var
)
2516 if (!var || var
is adparent || var
.isModule())
2520 buf
.writestring("::");
2523 override void visit(AST
.CallExp e
)
2525 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2527 // Dereferencing function pointers requires additional braces: (*f)(args)
2528 const isFp
= e
.e1
.isPtrExp();
2532 includeSymbol(outermostSymbol(e
.f
));
2536 if (isFp
) buf
.writeByte(')');
2538 assert(e
.arguments
);
2540 foreach (i
, arg
; *e
.arguments
)
2543 buf
.writestring(", ");
2549 override void visit(AST
.DotVarExp e
)
2551 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2553 if (auto sym
= symbolFromType(e
.e1
.type
))
2554 includeSymbol(outermostSymbol(sym
));
2556 // Accessing members through a pointer?
2557 if (auto pe
= e
.e1
.isPtrExp
)
2560 buf
.writestring("->");
2568 // Should only be used to access non-static members
2569 assert(e
.var
.isThis());
2571 writeIdentifier(e
.var
, true);
2574 override void visit(AST
.DotIdExp e
)
2576 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2579 buf
.writestring("::");
2580 buf
.writestring(e
.ident
.toChars());
2583 override void visit(AST
.ScopeExp e
)
2585 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2587 // Usually a template instance in a TemplateDeclaration
2588 if (auto ti
= e
.sds
.isTemplateInstance())
2591 writeFullName(e
.sds
);
2594 override void visit(AST
.NullExp e
)
2596 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2598 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
2599 buf
.writestring("nullptr");
2601 buf
.writestring("NULL");
2604 override void visit(AST
.ArrayLiteralExp e
)
2606 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2607 buf
.writestring("arrayliteral");
2610 override void visit(AST
.StringExp e
)
2612 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2620 foreach (i
; 0 .. e
.len
)
2622 writeCharLiteral(*buf
, e
.getCodeUnit(i
));
2627 override void visit(AST
.RealExp e
)
2629 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2631 import dmd
.root
.ctfloat
: CTFloat
;
2633 // Special case NaN and Infinity because floatToBuffer
2634 // uses D literals (`nan` and `infinity`)
2635 if (CTFloat
.isNaN(e
.value
))
2637 buf
.writestring("NAN");
2639 else if (CTFloat
.isInfinity(e
.value
))
2641 if (e
.value
< CTFloat
.zero
)
2643 buf
.writestring("INFINITY");
2648 // Hex floating point literals were introduced in C++ 17
2649 const allowHex
= global
.params
.cplusplus
>= CppStdRevision
.cpp17
;
2650 floatToBuffer(e
.type
, e
.value
, *buf
, allowHex
);
2654 override void visit(AST
.IntegerExp e
)
2656 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2657 visitInteger(e
.toInteger
, e
.type
);
2660 /// Writes `v` as type `t` into `buf`
2661 private void visitInteger(dinteger_t v
, AST
.Type t
)
2663 debug (Debug_DtoH
) mixin(traceVisit
!t
);
2668 auto te
= cast(AST
.TypeEnum
)t
;
2669 buf
.writestring("(");
2670 enumToBuffer(te
.sym
);
2671 buf
.writestring(")");
2672 visitInteger(v
, te
.sym
.memtype
);
2675 buf
.writestring(v ?
"true" : "false");
2678 buf
.printf("%d", cast(byte)v
);
2681 buf
.printf("%uu", cast(ubyte)v
);
2684 buf
.printf("%d", cast(short)v
);
2688 buf
.printf("%uu", cast(ushort)v
);
2692 buf
.printf("%d", cast(int)v
);
2695 buf
.printf("%uu", cast(uint)v
);
2698 buf
.printf("%lldLL", v
);
2701 buf
.printf("%lluLLU", v
);
2704 if (v
> 0x20 && v
< 0x80)
2705 buf
.printf("'%c'", cast(int)v
);
2707 buf
.printf("%uu", cast(ubyte)v
);
2715 override void visit(AST
.StructLiteralExp sle
)
2717 debug (Debug_DtoH
) mixin(traceVisit
!sle
);
2719 const isUnion
= sle
.sd
.isUnionDeclaration();
2720 sle
.sd
.type
.accept(this);
2722 foreach(i
, e
; *sle
.elements
)
2725 buf
.writestring(", ");
2727 auto vd
= sle
.sd
.fields
[i
];
2729 // Expression may be null for unspecified elements
2731 e
= findDefaultInitializer(vd
);
2733 printExpressionFor(vd
.type
, e
);
2735 // Only emit the initializer of the first union member
2742 /// Finds the default initializer for the given VarDeclaration
2743 private static AST
.Expression
findDefaultInitializer(AST
.VarDeclaration vd
)
2745 if (vd
._init
&& !vd
._init
.isVoidInitializer())
2746 return AST
.initializerToExpression(vd
._init
);
2747 else if (auto ts
= vd
.type
.isTypeStruct())
2749 if (!ts
.sym
.noDefaultCtor
&& !ts
.sym
.isUnionDeclaration())
2751 // Generate a call to the default constructor that we've generated.
2752 auto sle
= new AST
.StructLiteralExp(Loc
.initial
, ts
.sym
, new AST
.Expressions(0));
2757 return vd
.type
.defaultInitLiteral(Loc
.initial
);
2760 return vd
.type
.defaultInitLiteral(Loc
.initial
);
2763 static if (__VERSION__
< 2092)
2765 private void ignored(const char* format
, ...) nothrow
2767 this.ignoredCounter
++;
2769 import core
.stdc
.stdarg
;
2774 va_start(ap
, format
);
2775 buf
.writestring("// Ignored ");
2776 buf
.vprintf(format
, ap
);
2783 /// Writes a formatted message into `buf` if `printIgnored` is true
2784 /// and increments `ignoredCounter`
2786 private void ignored(const char* format
, ...) nothrow
2788 this.ignoredCounter
++;
2790 import core
.stdc
.stdarg
;
2795 va_start(ap
, format
);
2796 buf
.writestring("// Ignored ");
2797 buf
.vprintf(format
, ap
);
2804 * Determines whether `s` should be emitted. This requires that `sym`
2805 * - is `extern(C[++]`)
2806 * - is not instantiated from a template (visits the `TemplateDeclaration` instead)
2811 * Returns: whether `sym` should be emitted
2813 private bool shouldEmit(AST
.Dsymbol sym
)
2815 import dmd
.aggregate
: ClassKind
;
2818 printf("[shouldEmitAndMarkVisited enter] %s\n", sym
.toPrettyChars());
2819 scope(exit
) printf("[shouldEmitAndMarkVisited exit] %s\n", sym
.toPrettyChars());
2822 // Template *instances* should not be emitted
2823 if (sym
.isInstantiated())
2826 // Matching linkage (except extern(C) classes which don't make sense)
2827 if (linkage
== LINK
.cpp ||
(linkage
== LINK
.c
&& !sym
.isClassDeclaration()))
2830 // Check against the internal information which might be missing, e.g. inside of template declarations
2831 if (auto dec = sym
.isDeclaration())
2833 const l
= dec.resolvedLinkage();
2834 return l
== LINK
.cpp || l
== LINK
.c
;
2837 if (auto ad
= sym
.isAggregateDeclaration())
2838 return ad
.classKind
== ClassKind
.cpp
;
2844 * Determines whether `s` should be emitted. This requires that `sym`
2845 * - was not visited before
2846 * - is `extern(C[++]`)
2847 * - is not instantiated from a template (visits the `TemplateDeclaration` instead)
2848 * The result is cached in the visited nodes array.
2853 * Returns: whether `sym` should be emitted
2855 private bool shouldEmitAndMarkVisited(AST
.Dsymbol sym
)
2859 printf("[shouldEmitAndMarkVisited enter] %s\n", sym
.toPrettyChars());
2860 scope(exit
) printf("[shouldEmitAndMarkVisited exit] %s\n", sym
.toPrettyChars());
2863 auto statePtr
= (cast(void*) sym
) in visited
;
2865 // `sym` was already emitted or skipped and isn't required
2866 if (statePtr
&& (*statePtr ||
!mustEmit
))
2869 // Template *instances* should not be emitted, forward to the declaration
2870 if (auto ti
= sym
.isInstantiated())
2872 auto td
= findTemplateDeclaration(ti
);
2878 // Required or matching linkage (except extern(C) classes which don't make sense)
2879 bool res
= mustEmit || linkage
== LINK
.cpp ||
(linkage
== LINK
.c
&& !sym
.isClassDeclaration());
2882 // Check against the internal information which might be missing, e.g. inside of template declarations
2883 if (auto dec = sym
.isDeclaration())
2885 const l
= dec.resolvedLinkage();
2886 res
= (l
== LINK
.cpp || l
== LINK
.c
);
2890 // Remember result for later calls
2894 visited
[(cast(void*) sym
)] = res
;
2896 // Print a warning when the symbol is ignored for the first time
2897 // Might not be correct if it is required by symbol the is visited
2898 // AFTER the current node
2899 if (!statePtr
&& !res
)
2900 ignored("%s %s because of linkage", sym
.kind(), sym
.toPrettyChars());
2906 * Ensures that `sym` is declared before the current position in `buf` by
2907 * either creating a forward reference in `fwdbuf` if possible or
2908 * calling `includeSymbol` to emit the entire declaration into `donebuf`.
2910 private void ensureDeclared(AST
.Dsymbol sym
)
2912 auto par
= sym
.toParent2();
2913 auto ed
= sym
.isEnumDeclaration();
2915 // Eagerly include the symbol if we cannot create a valid forward declaration
2916 // Forwarding of scoped enums requires C++11 or above
2917 if (!forwarding ||
(par
&& !par
.isModule()) ||
(ed
&& global
.params
.cplusplus
< CppStdRevision
.cpp11
))
2919 // Emit the entire enclosing declaration if any
2920 includeSymbol(outermostSymbol(sym
));
2924 auto ti
= sym
.isInstantiated();
2925 auto td
= ti ?
findTemplateDeclaration(ti
) : null;
2926 auto check
= cast(void*) (td ? td
: sym
);
2928 // Omit redundant fwd-declaration if we already emitted the entire declaration
2929 if (visited
.get(check
, false))
2932 // Already created a fwd-declaration?
2933 if (check
in forwarded
)
2935 forwarded
[check
] = true;
2937 // Print template<...>
2942 printTemplateParams(td
);
2946 // Determine the kind of symbol that is forwared: struct, ...
2949 if (auto ad
= sym
.isAggregateDeclaration())
2951 // Look for extern(C++, class) <some aggregate>
2952 if (ad
.cppmangle
== CPPMANGLE
.def
)
2954 else if (ad
.cppmangle
== CPPMANGLE
.asStruct
)
2961 // Only called from enumToBuffer, so should always be emitted as an actual enum
2962 kind
= "enum class";
2965 kind
= sym
.kind(); // Should be unreachable but just to be sure
2967 fwdbuf
.writestring(kind
);
2968 fwdbuf
.writeByte(' ');
2969 fwdbuf
.writestring(sym
.toChars());
2970 fwdbuf
.writestringln(";");
2974 * Writes the qualified name of `sym` into `buf` including parent
2975 * symbols and template parameters.
2979 * mustInclude = whether sym may not be forward declared
2981 private void writeFullName(AST
.Dsymbol sym
, const bool mustInclude
= false)
2985 assert(sym
.ident
, sym
.toString());
2986 // Should never be called directly with a TI, only onemember
2987 assert(!sym
.isTemplateInstance(), sym
.toString());
2993 printf("[writeFullName enter] %s\n", sym
.toPrettyChars());
2994 scope(exit
) printf("[writeFullName exit] %s\n", sym
.toPrettyChars());
2997 // Explicit `pragma(mangle, "<some string>` overrides the declared name
2998 if (auto mn
= getMangleOverride(sym
))
2999 return buf
.writestring(mn
);
3001 /// Checks whether `sym` is nested in `par` and hence doesn't need the FQN
3002 static bool isNestedIn(AST
.Dsymbol sym
, AST
.Dsymbol par
)
3008 par
= par
.toParent();
3012 AST
.TemplateInstance ti
;
3015 // Check if the `sym` is nested into another symbol and hence requires `Parent::sym`
3016 if (auto par
= sym
.toParent())
3018 // toParent() yields the template instance if `sym` is the onemember of a TI
3019 ti
= par
.isTemplateInstance();
3021 // Skip the TI because Foo!int.Foo is folded into Foo<int>
3022 if (ti
) par
= ti
.toParent();
3024 // Prefix the name with any enclosing declaration
3025 // Stop at either module or enclosing aggregate
3026 nested
= !par
.isModule();
3027 if (nested
&& !isNestedIn(par
, adparent
))
3029 writeFullName(par
, true);
3030 buf
.writestring("::");
3036 // Cannot forward the symbol when called recursively
3037 // for a nested symbol
3041 ensureDeclared(sym
);
3047 buf
.writestring(sym
.ident
.toString());
3050 /// Returns: Explicit mangling for `sym` if present
3051 extern(D
) static const(char)[] getMangleOverride(const AST
.Dsymbol sym
) @safe
3053 if (auto decl
= sym
.isDeclaration())
3054 return decl
.mangleOverride
;
3060 /// Namespace for identifiers used to represent special enums in C++
3063 __gshared Identifier c_long
;
3064 __gshared Identifier c_ulong
;
3065 __gshared Identifier c_longlong
;
3066 __gshared Identifier c_ulonglong
;
3067 __gshared Identifier c_long_double
;
3068 __gshared Identifier c_char
;
3069 __gshared Identifier c_wchar_t
;
3070 __gshared Identifier c_complex_float
;
3071 __gshared Identifier c_complex_double
;
3072 __gshared Identifier c_complex_real
;
3076 c_long
= Identifier
.idPool("__c_long");
3077 c_ulong
= Identifier
.idPool("__c_ulong");
3078 c_longlong
= Identifier
.idPool("__c_longlong");
3079 c_ulonglong
= Identifier
.idPool("__c_ulonglong");
3080 c_long_double
= Identifier
.idPool("__c_long_double");
3081 c_wchar_t
= Identifier
.idPool("__c_wchar_t");
3082 c_char
= Identifier
.idPool("__c_char");
3083 c_complex_float
= Identifier
.idPool("__c_complex_float");
3084 c_complex_double
= Identifier
.idPool("__c_complex_double");
3085 c_complex_real
= Identifier
.idPool("__c_complex_real");
3089 /// Initializes all data structures used by the header generator
3092 __gshared
bool initialized
;
3102 /// Writes `#if <content>` into the supplied buffer
3103 void hashIf(ref OutBuffer buf
, string content
) @safe
3105 buf
.writestring("#if ");
3106 buf
.writestringln(content
);
3109 /// Writes `#elif <content>` into the supplied buffer
3110 void hashElIf(ref OutBuffer buf
, string content
) @safe
3112 buf
.writestring("#elif ");
3113 buf
.writestringln(content
);
3116 /// Writes `#endif` into the supplied buffer
3117 void hashEndIf(ref OutBuffer buf
) @safe
3119 buf
.writestringln("#endif");
3122 /// Writes `#define <content>` into the supplied buffer
3123 void hashDefine(ref OutBuffer buf
, string content
) @safe
3125 buf
.writestring("#define ");
3126 buf
.writestringln(content
);
3129 /// Writes `#include <content>` into the supplied buffer
3130 void hashInclude(ref OutBuffer buf
, string content
) @safe
3132 buf
.writestring("#include ");
3133 buf
.writestringln(content
);
3136 /// Determines whether `ident` is a reserved keyword in C++
3137 /// Returns: the kind of keyword or `null`
3138 const(char*) keywordClass(const Identifier ident
)
3143 const name
= ident
.toString();
3158 return "special operator in C++";
3164 case "dynamic_cast":
3172 case "reinterpret_cast":
3181 return "keyword in C++";
3183 // Common macros imported by this header
3187 return "default macro in C++";
3198 case "static_assert":
3199 case "thread_local":
3201 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
3202 return "keyword in C++11";
3209 // Concepts-related keywords
3212 // Coroutines-related keywords
3216 if (global
.params
.cplusplus
>= CppStdRevision
.cpp20
)
3217 return "keyword in C++20";
3224 //case "_Complex": // handled above in C++
3228 case "_Static_assert":
3229 case "_Thread_local":
3232 //case "__...": handled in default case below
3233 return "Keyword in C";
3236 // Identifiers starting with __ are reserved
3237 if (name
.length
>= 2 && name
[0..2] == "__")
3238 return "reserved identifier in C++";
3244 /// Finds the outermost symbol if `sym` is nested.
3245 /// Returns `sym` if it appears at module scope
3246 ASTCodegen
.Dsymbol
outermostSymbol(ASTCodegen
.Dsymbol sym
)
3251 auto par
= sym
.toParent();
3252 if (!par || par
.isModule())
3258 /// Fetches the symbol for user-defined types from the type `t`
3259 /// if `t` is either `TypeClass`, `TypeStruct` or `TypeEnum`
3260 ASTCodegen
.Dsymbol
symbolFromType(ASTCodegen
.Type t
) @safe
3262 if (auto tc
= t
.isTypeClass())
3264 if (auto ts
= t
.isTypeStruct())
3266 if (auto te
= t
.isTypeEnum())
3272 * Searches `sym` for a member with the given name.
3274 * This method usually delegates to `Dsymbol.search` but might also
3275 * manually check the members if the symbol did not receive semantic
3279 * sym = symbol to search
3280 * name = identifier of the requested symbol
3282 * Returns: the symbol or `null` if not found
3284 ASTCodegen
.Dsymbol
findMember(ASTCodegen
.Dsymbol sym
, Identifier name
)
3286 if (auto mem
= sym
.search(Loc
.initial
, name
, ASTCodegen
.IgnoreErrors
))
3289 // search doesn't work for declarations inside of uninstantiated
3290 // `TemplateDeclaration`s due to the missing symtab.
3291 if (sym
.semanticRun
>= ASTCodegen
.PASS
.semanticdone
)
3294 // Manually check the members if present
3295 auto sds
= sym
.isScopeDsymbol();
3296 if (!sds ||
!sds
.members
)
3299 /// Recursively searches for `name` without entering nested aggregates, ...
3300 static ASTCodegen
.Dsymbol
search(ASTCodegen
.Dsymbols
* members
, Identifier name
)
3302 foreach (mem
; *members
)
3304 if (mem
.ident
== name
)
3307 // Look inside of private:, ...
3308 if (auto ad
= mem
.isAttribDeclaration())
3310 if (auto s
= search(ad
.decl
, name
))
3317 return search(sds
.members
, name
);
3322 /// Generates code to trace the entry and exit of the enclosing `visit` function
3323 string
traceVisit(alias node
)()
3325 const type
= typeof(node
).stringof
;
3326 const method
= __traits(hasMember
, node
, "toPrettyChars") ?
"toPrettyChars" : "toChars";
3327 const arg
= __traits(identifier
, node
) ~ '.' ~ method
;
3329 return `printf("[` ~ type
~ ` enter] %s\n", ` ~ arg
~ `());
3330 scope(exit) printf("[` ~ type
~ ` exit] %s\n", ` ~ arg
~ `());`;