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
14 import core
.stdc
.stdio
;
15 import core
.stdc
.string
;
16 import core
.stdc
.ctype
;
18 import dmd
.astcodegen
;
20 import dmd
.arraytypes
;
23 import dmd
.dsymbolsem
;
28 import dmd
.identifier
;
30 import dmd
.root
.filename
;
34 import dmd
.common
.outbuffer
;
39 // Generate asserts to validate the header
40 //debug = Debug_DtoH_Checks;
43 * Generates a C++ header containing bindings for all `extern(C[++])` declarations
44 * found in the supplied modules.
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
)
64 // enable indent by spaces on buffers
70 scope v
= new ToCppBuffer(&fwd
, &done
, &decl
);
72 // Conditionally include another buffer for sanity checks
73 debug (Debug_DtoH_Checks
)
76 check
.doindent
= true;
88 if (global
.params
.cxxhdr
.fullOutput
)
89 buf
.printf("// Automatically generated by %s Compiler v%d", global
.compileEnv
.vendor
.ptr
, global
.versionNumber());
91 buf
.printf("// Automatically generated by %s Compiler", global
.compileEnv
.vendor
.ptr
);
95 buf
.writestringln("#pragma once");
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)
107 #ifdef CUSTOM_D_ARRAY_TYPE
108 #define _d_dynamicArray CUSTOM_D_ARRAY_TYPE
110 /// Represents a D [] array
112 struct _d_dynamicArray final
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);
127 const T& operator[](const size_t idx) const {
128 assert(idx < length);
137 hashIf(buf
, "!defined(_d_real)");
139 hashDefine(buf
, "_d_real long double");
144 // buf.writestringln("// fwd:");
149 // buf.writestringln("// done:");
152 // buf.writestringln("// decl:");
155 debug (Debug_DtoH_Checks
)
157 // buf.writestringln("// check:");
161 size_t getSlotNumber(int dummy, ...)
167 void *f = va_arg(ap, void*);
168 for (size_t i = 0; ; i++)
170 if ( (*(void***)&c)[i] == f)
186 // prevent trailing newlines
188 while (buf
.length
>= 4 && buf
[$-4..$] == "\r\n\r\n")
189 buf
.remove(buf
.length
- 2, 2);
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
203 const(char)[] name
= FileName
.combine(global
.params
.cxxhdr
.dir
, global
.params
.cxxhdr
.name
);
204 if (!writeFile(Loc
.initial
, name
, buf
[]))
211 /****************************************************
212 * Visitor that writes bindings for `extern(C[++]` declarations.
214 extern(C
++) final class ToCppBuffer
: Visitor
216 alias visit
= Visitor
.visit
;
227 /// Namespace providing the actual AST nodes
228 alias AST
= ASTCodegen
;
233 /// Forward declared nodes (which might not be emitted yet)
234 bool[void*] forwarded
;
236 /// Buffer for forward declarations
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`)
246 /// Default buffer for the currently visited declaration
249 /// The generated header uses `real` emitted as `_d_real`?
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)
272 /// Original type of the currently visited declaration
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
284 /// Currently visited types are required by another declaration
285 /// and hence must be emitted
288 /// Processing a type that can be forward referenced
291 /// Inside of an anonymous struct/union (AnonDeclaration)
292 bool inAnonymousDecl
;
295 /// Informations about the current context in the AST
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
304 foreach(member
; __traits(allMembers
, Context
))
306 result
~= "ref auto " ~ member
~ "() { return context." ~ member
~ "; }\n";
310 mixin(generateMembers());
312 this(OutBuffer
* fwdbuf
, OutBuffer
* donebuf
, OutBuffer
* buf
) scope
314 this.fwdbuf
= fwdbuf
;
315 this.donebuf
= donebuf
;
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
)
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
;
338 // Temporary replacement for `buf` which is appended to `donebuf`
340 decl
.doindent
= true;
342 scope (exit
) donebuf
.write(&decl
);
344 auto ctxStash
= this.context
;
345 auto bufStash
= this.buf
;
347 this.context
= Context
.init
;
349 this.mustEmit
= true;
353 this.context
= ctxStash
;
357 /// Determines what kind of enum `type` is (see `EnumKind`)
358 private EnumKind
getEnumKind(AST
.Type type
)
360 if (type
) switch (type
.ty
)
365 AST
.Tchar
, AST
.Twchar
, AST
.Tdchar
,
366 AST
.Tint8
, AST
.Tuns8
,
367 AST
.Tint16
, AST
.Tuns16
,
369 AST
.Tint64
, AST
.Tuns64
:
370 return EnumKind
.Numeric
;
373 return EnumKind
.String
;
376 return EnumKind
.Enum
;
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())
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
;
400 /// Writes a final `;` and insert an empty line outside of aggregates
401 private void writeDeclEnd() @safe
403 buf
.writestringln(";");
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
)
418 switch(kind
) with(AST
.Visibility
.Kind
)
421 if (this.currentVisibility
== AST
.Visibility
.Kind
.private_
)
423 this.currentVisibility
= AST
.Visibility
.Kind
.private_
;
427 case package_
, protected_
:
428 if (this.currentVisibility
== AST
.Visibility
.Kind
.protected_
)
430 this.currentVisibility
= AST
.Visibility
.Kind
.protected_
;
431 token
= "protected:";
434 case undefined
, public_
, export_
:
435 if (this.currentVisibility
== AST
.Visibility
.Kind
.public_
)
437 this.currentVisibility
= AST
.Visibility
.Kind
.public_
;
442 printf("Unexpected visibility: %d!\n", kind
);
447 buf
.writestringln(token
);
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
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)
476 void warnCxxCompat(const(char)* reason
)
484 __gshared
bool warned
= false;
485 warning(loc
, "%s `%s` is a %s", kind
, ident
.toChars(), reason
);
489 warningSupplemental(loc
, "The generated C++ header will contain " ~
490 "identifiers that are keywords in C++");
495 if (global
.params
.warnings
!= DiagnosticReporting
.off || canFix
)
497 // Warn about identifiers that are keywords in C++.
498 if (auto kc
= keywordClass(ident
))
501 buf
.writestring(ident
.toString());
506 /// Checks whether `t` is a type that can be exported to C++
507 private bool isSupportedType(AST
.Type t
)
523 return isSupportedType((cast(AST
.TypeNext
) t
).next
);
528 auto tf
= cast(AST
.TypeFunction
) t
;
529 if (!isSupportedType(tf
.next
))
531 foreach (_
, param
; tf
.parameterList
)
533 if (!isSupportedType(param
.type
))
539 // Noreturn has a different mangling
542 // _Imaginary is C only.
543 case AST
.Timaginary32
:
544 case AST
.Timaginary64
:
545 case AST
.Timaginary80
:
552 override void visit(AST
.Dsymbol 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())
576 ad
= sym
.isAliasDeclaration();
578 // Might be an alias to a basic type
579 if (ad
&& !ad
.aliassym
&& ad
.type
)
583 // Restricted to types and other aliases
584 if (!sym
.isScopeDsymbol() && !sym
.isAggregateDeclaration())
585 return "only supports types";
587 // Write `using <alias_> = `<sym>`
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());
600 // Only missing without semantic analysis
601 // FIXME: Templates need work due to missing parent & imported module
605 ignored("`%s` because it's inside of a template declaration", i
.toChars());
609 // Non-public imports don't create new symbols, include as needed
610 if (i
.visibility
.kind
< AST
.Visibility
.Kind
.public_
)
613 // Symbols from static imports should be emitted inline
617 const isLocal
= !i
.parent
.isModule();
619 // Need module for symbol lookup
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
)
650 if (auto err
= writeImport(sym
, sym
.ident
))
651 ignored("public import for `%s` because `using` %s", sym
.ident
.toChars(), err
);
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
665 // Detect the assigned name for renamed import
666 auto alias_
= i
.aliases
[idx
];
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);
685 if (adparent || s
.visible().kind
>= AST
.Visibility
.Kind
.public_
)
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
);
705 linkage
= ld
.linkage
;
706 visit(cast(AST
.AttribDeclaration
)ld
);
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_
)
732 override void visit(AST
.FuncDeclaration fd
)
734 debug (Debug_DtoH
) mixin(traceVisit
!fd
);
736 if (cast(void*)fd
in visited
)
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())
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());
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());
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\" ");
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);",
818 if (adparent
&& fd
.isDisabled
&& global
.params
.cplusplus
< CppStdRevision
.cpp11
)
819 writeProtection(AST
.Visibility
.Kind
.private_
);
820 funcToBuffer(tf
, fd
);
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");
830 buf
.writestring(" override");
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_
);
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
++);
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_
);
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
))
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);
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());
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
;
916 // Just a precaution, implicit type without initializer should be rejected
920 if (auto ei
= vd
._init
.isExpInitializer())
923 // Can happen if the expression needs further semantic
926 ignored("%s because the type could not be determined", vd
.toPrettyChars());
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
));
944 writeProtection(vd
.visibility
.kind
);
948 case EnumKind
.Int
, EnumKind
.Numeric
:
949 // 'enum : type' is only available from C++-11 onwards.
950 if (global
.params
.cplusplus
< CppStdRevision
.cpp11
)
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(" };");
962 case EnumKind
.String
, EnumKind
.Enum
:
963 buf
.writestring("static ");
964 auto target
= determineEnumType(type
);
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(";");
975 ignored("enum `%s` because type `%s` is currently not supported for enum constants.", vd
.toPrettyChars(), type
.toChars());
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());
992 if (vd
.mangleOverride
&& vdLinkage
!= LINK
.c
)
994 ignored("variable %s because C++ doesn't support explicit mangling", vd
.toPrettyChars());
997 if (!isSupportedType(type
))
999 ignored("variable %s because its type cannot be mapped to C++", vd
.toPrettyChars());
1002 if (auto kc
= keywordClass(vd
.ident
))
1004 ignored("variable %s because its name is a %s", vd
.toPrettyChars(), kc
);
1007 writeProtection(vd
.visibility
.kind
);
1008 if (vdLinkage
== LINK
.c
)
1009 buf
.writestring("extern \"C\" ");
1011 buf
.writestring("extern ");
1013 buf
.writestring("static ");
1014 typeToBuffer(type
, vd
);
1021 writeProtection(vd
.visibility
.kind
);
1022 typeToBuffer(type
, vd
, true);
1023 buf
.writestringln(";");
1025 debug (Debug_DtoH_Checks
)
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);",
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
)
1055 if (!shouldEmitAndMarkVisited(ad
))
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
);
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
);
1085 if (auto ti
= ad
.aliassym
.isTemplateInstance())
1090 if (auto sd
= ad
.aliassym
.isStructDeclaration())
1092 buf
.writestring("typedef ");
1093 sd
.type
.accept(this);
1094 buf
.writestring(" ");
1095 writeIdentifier(ad
);
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());
1107 printTemplateParams(td
);
1108 buf
.writestring("using ");
1109 writeIdentifier(ad
);
1110 buf
.writestring(" = ");
1114 foreach (const idx
, const p
; *td
.parameters
)
1117 buf
.writestring(", ");
1118 writeIdentifier(p
.ident
, p
.loc
, "parameter", true);
1120 buf
.writestringln(">;");
1124 auto fd
= ad
.aliassym
.isFuncDeclaration();
1126 if (fd
&& (fd
.isGenerated() || fd
.isDtorDeclaration()))
1128 // Ignore. It's taken care of while visiting FuncDeclaration
1132 // Recognize member function aliases, e.g. alias visit = Parent.visit;
1135 auto pd
= fd
.isMember();
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
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
);
1164 buf
.writestring(fd
.ident
.toChars());
1165 buf
.writestringln(";");
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
);
1191 buf
.writestring("{");
1194 foreach(decl
;(*members
))
1199 buf
.writestring("}");
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("{");
1214 foreach (s
; *ad
.decl
)
1219 buf
.writestringln("};");
1222 private bool memberField(AST
.VarDeclaration vd
) @safe
1224 if (!vd
.type ||
!vd
.type
.deco ||
!vd
.ident
)
1228 if (vd
.type
.ty
== AST
.Tfunction
)
1230 if (vd
.type
.ty
== AST
.Tsarray
)
1235 override void visit(AST
.StructDeclaration sd
)
1237 debug (Debug_DtoH
) mixin(traceVisit
!sd
);
1239 if (!shouldEmitAndMarkVisited(sd
))
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 ");
1253 buf
.writestring(structAsClass ?
"class " : "struct ");
1255 writeIdentifier(sd
);
1258 buf
.writestringln(";");
1263 // D structs are always final
1264 if (!sd
.isUnionDeclaration())
1265 buf
.writestring(" final");
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
;
1276 auto save
= adparent
;
1279 foreach (m
; *sd
.members
)
1283 // Generate default ctor
1284 if (!sd
.noDefaultCtor
&& !sd
.isUnionDeclaration())
1286 writeProtection(AST
.Visibility
.Kind
.public_
);
1287 buf
.printf("%s()", sd
.ident
.toChars());
1291 foreach (vd
; sd
.fields
)
1293 if (!memberField(vd
) || vd
.overlapped
)
1297 if (!vd
._init
&& !vd
.type
.isTypeBasic() && !vd
.type
.isTypePointer
&& !vd
.type
.isTypeStruct
&&
1298 !vd
.type
.isTypeClass
&& !vd
.type
.isTypeDArray
&& !vd
.type
.isTypeSArray
)
1302 if (vd
._init
&& vd
._init
.isVoidInitializer())
1307 buf
.writestringln(" :");
1312 buf
.writestringln(",");
1314 writeIdentifier(vd
, true);
1319 auto e
= AST
.initializerToExpression(vd
._init
);
1320 printExpressionFor(vd
.type
, e
, true);
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());
1333 foreach (vd
; sd
.fields
)
1335 if (!memberField(vd
) || vd
.overlapped
)
1338 buf
.writestring(", ");
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
1346 buf
.writestring(" = ");
1347 printExpressionFor(vd
.type
, findDefaultInitializer(vd
));
1351 buf
.writestring(") :");
1356 foreach (vd
; sd
.fields
)
1358 if (!memberField(vd
) || vd
.overlapped
)
1364 buf
.writestringln(",");
1366 writeIdentifier(vd
, true);
1368 writeIdentifier(vd
, true);
1372 buf
.writestringln("{}");
1379 buf
.writestringln("};");
1381 popAlignToBuffer(sd
.alignment
);
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
)
1391 const sn
= sd
.ident
.toChars();
1392 const sz
= sd
.size(Loc
.initial
);
1393 checkbuf
.printf("assert(sizeof(%s) == %llu);", sn
, sz
);
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()))
1414 buf
.printf("#pragma pack(push, %d)", alignment
.get());
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()))
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
))
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);
1461 writeFullName(base
.sym
);
1467 buf
.writestring(";");
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
;
1483 foreach (m
; *cd
.members
)
1490 buf
.writestringln("};");
1494 override void visit(AST
.EnumDeclaration ed
)
1496 debug (Debug_DtoH
) mixin(traceVisit
!ed
);
1498 if (!shouldEmitAndMarkVisited(ed
))
1503 //ignored("%s because it is a special C++ type", ed.toPrettyChars());
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();
1519 else if (m
.type
!is type
)
1526 EnumKind kind
= getEnumKind(type
);
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());
1536 // Opaque enum defaults to int but the type might not be set
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());
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
)
1567 buf
.writestring(" class ");
1568 writeIdentifier(ed
);
1570 if (kind
== EnumKind
.Numeric
)
1572 buf
.writestring(" : ");
1573 determineEnumType(type
).accept(this);
1576 else if (!isAnonymous
)
1579 writeIdentifier(ed
);
1584 buf
.writestring("namespace");
1588 writeIdentifier(ed
);
1591 // Opaque enums have no members, hence skip the body
1594 buf
.writestringln(";");
1600 buf
.writestringln("{");
1604 // emit constant for each member
1605 if (!manifestConstants
)
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
);
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(" };");
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(";");
1658 if (!manifestConstants
)
1660 // write the enum tail
1661 if (!manifestConstants
)
1662 buf
.writestring("};");
1667 override void visit(AST
.EnumMember em
)
1671 // Members of anonymous members are reachable without referencing the
1672 // EnumDeclaration, e.g. public import foo : someEnumMember;
1673 if (em
.ed
.isAnonymous())
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`.
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)
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())
1711 this.ident
= Id
.outer
;
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
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
1729 if (auto ti
= taa
.index
.isTypeIdentifier())
1734 auto sym
= findSymbol(id
, adparent ? adparent
: tdparent
);
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
1747 type
= taa
.next
; // visit the element type, length is written below
1751 printf("Resolved unexpected symbol while determining static array length: %s\n", sym
.toChars());
1762 // Custom identifier doesn't need further checks
1763 if (this.ident
!is s
.ident
)
1764 buf
.writestring(this.ident
.toString());
1766 writeIdentifier(s
, canFixup
);
1771 // Size is either taken from the type or resolved above
1772 auto tsa
= t
.isTypeSArray();
1773 if (tsa || customLength
)
1777 tsa
.dim
.accept(this);
1779 writeFullName(customLength
);
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());
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());
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");
1835 buf
.writestring("void*");
1839 override void visit(AST
.TypeTypeof t
)
1841 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1847 t
.exp
.type
.accept(this);
1849 else if (t
.exp
.isThisExp())
1851 // Short circuit typeof(this) => <Aggregate name>
1853 buf
.writestring(adparent
.ident
.toChars());
1857 // Relying on C++'s typeof might produce wrong results
1858 // but it's the best we've got here.
1859 buf
.writestring("typeof(");
1865 override void visit(AST
.TypeBasic t
)
1867 debug (Debug_DtoH
) mixin(traceVisit
!t
);
1869 if (t
.isConst() || t
.isImmutable())
1870 buf
.writestring("const ");
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;
1890 typeName
= "_d_real";
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";
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";
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");
1925 // Pointer targets can be forward referenced
1926 const fwdSave
= forwarding
;
1928 scope (exit
) forwarding
= fwdSave
;
1930 t
.next
.accept(this);
1931 if (t
.next
.ty
!= AST
.Tfunction
)
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);
1957 buf
.writestring(ident
.toChars());
1961 foreach (i
, fparam
; tf
.parameterList
)
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("...");
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
);
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");
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
)
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
))
2069 foreach (o
; *ti
.tiargs
)
2074 buf
.writestring(ti
.name
.toChars());
2076 foreach (i
, o
; *ti
.tiargs
)
2079 buf
.writestring(", ");
2080 if (auto tt
= AST
.isType(o
))
2091 buf
.writestring(" >");
2094 override void visit(AST
.TemplateDeclaration td
)
2096 debug (Debug_DtoH
) mixin(traceVisit
!td
);
2098 if (!shouldEmitAndMarkVisited(td
))
2101 if (!td
.parameters ||
!td
.onemember ||
(!td
.onemember
.isStructDeclaration
&& !td
.onemember
.isClassDeclaration
&& !td
.onemember
.isFuncDeclaration
))
2103 visit(cast(AST
.Dsymbol
)td
);
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
);
2117 auto save
= tdparent
;
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
);
2132 /// Writes the template<...> header for the supplied template declaration
2133 private void printTemplateParams(const AST
.TemplateDeclaration td
)
2135 buf
.writestring("template <");
2137 foreach (p
; *td
.parameters
)
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; }
2160 if (auto td
= findTemplateDeclaration(tm
))
2161 members
= td
.members
; // Emit members of the template
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
)
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
)
2196 if (auto mem
= findMember(par
, name
))
2205 private AST
.Dsymbol
findSymbol(Identifier name
)
2209 sym
= findSymbol(name
, adparent
);
2211 if (!sym
&& tdparent
)
2212 sym
= findSymbol(name
, tdparent
);
2217 /// Finds the template declaration for instance `ti`
2218 private AST
.TemplateDeclaration
findTemplateDeclaration(AST
.TemplateInstance ti
)
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
;
2238 scope (exit
) forwarding
= fwdSave
;
2240 if (t
.isConst() || t
.isImmutable())
2241 buf
.writestring("const ");
2242 writeFullName(t
.sym
);
2244 if (t
.isConst() || t
.isImmutable())
2245 buf
.writestring(" const");
2249 * Writes the function signature to `buf`.
2252 * fd = the function to print
2255 private void funcToBuffer(AST
.TypeFunction tf
, AST
.FuncDeclaration fd
)
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())
2271 buf
.writestring(adparent
.toChars());
2274 assert(fd
.isDtorDeclaration());
2275 buf
.writestring("()");
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);
2288 writeIdentifier(fd
);
2292 foreach (i
, fparam
; tf
.parameterList
)
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("...");
2311 override void visit(AST
.Parameter p
)
2313 debug (Debug_DtoH
) mixin(traceVisit
!p
);
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_
))
2329 // FIXME: Parameter is missing a Loc
2330 writeIdentifier(ident
, Loc
.initial
, "parameter", true);
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
;
2341 printExpressionFor(p
.type
, p
.defaultArg
);
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.
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
;
2371 // Defensively assume that the cast is required
2374 // Conversions from enum class to base type require static_cast
2375 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
&&
2376 source
.isTypeEnum
&& !target
.isTypeEnum
)
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())
2390 // Don't emit, use default ctor
2392 else if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
2394 // Prefer initializer list
2395 buf
.writestring("{}");
2399 // Write __d_dynamic_array<TYPE>()
2401 buf
.writestring("()");
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
;
2415 buf
.writestring("{ ");
2419 buf
.writestring("( ");
2423 buf
.printf("%zu, ", se
.len
);
2427 buf
.writestring(initList ?
" }" : " )");
2432 else if (auto ce
= exp
.isCastExp())
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);
2441 // Fallback, not necessarily correct but the best we've got here
2442 target
.accept(this);
2443 buf
.writestring(") ");
2446 else if (needsCast(target
, exp
))
2448 buf
.writestring("static_cast<");
2449 target
.accept(this);
2450 buf
.writestring(">(");
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
));
2477 override void visit(AST
.BinExp e
)
2479 debug (Debug_DtoH
) mixin(traceVisit
!e
);
2483 buf
.writestring(expToString(e
.op
));
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 "!=";
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
2507 includeSymbol(e
.var
);
2508 writeIdentifier(e
.var
, true);
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())
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();
2533 includeSymbol(outermostSymbol(e
.f
));
2537 if (isFp
) buf
.writeByte(')');
2539 assert(e
.arguments
);
2541 foreach (i
, arg
; *e
.arguments
)
2544 buf
.writestring(", ");
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
)
2561 buf
.writestring("->");
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
);
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())
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");
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
);
2621 foreach (i
; 0 .. e
.len
)
2623 writeCharLiteral(*buf
, e
.getCodeUnit(i
));
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
)
2644 buf
.writestring("INFINITY");
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
);
2669 auto te
= cast(AST
.TypeEnum
)t
;
2670 buf
.writestring("(");
2671 enumToBuffer(te
.sym
);
2672 buf
.writestring(")");
2673 visitInteger(v
, te
.sym
.memtype
);
2676 buf
.writestring(v ?
"true" : "false");
2679 buf
.printf("%d", cast(byte)v
);
2682 buf
.printf("%uu", cast(ubyte)v
);
2685 buf
.printf("%d", cast(short)v
);
2689 buf
.printf("%uu", cast(ushort)v
);
2693 buf
.printf("%d", cast(int)v
);
2696 buf
.printf("%uu", cast(uint)v
);
2699 buf
.printf("%lldLL", v
);
2702 buf
.printf("%lluLLU", v
);
2705 if (v
> 0x20 && v
< 0x80)
2706 buf
.printf("'%c'", cast(int)v
);
2708 buf
.printf("%uu", cast(ubyte)v
);
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);
2723 foreach(i
, e
; *sle
.elements
)
2726 buf
.writestring(", ");
2728 auto vd
= sle
.sd
.fields
[i
];
2730 // Expression may be null for unspecified elements
2732 e
= findDefaultInitializer(vd
);
2734 printExpressionFor(vd
.type
, e
);
2736 // Only emit the initializer of the first union member
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));
2758 return vd
.type
.defaultInitLiteral(Loc
.initial
);
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
;
2775 va_start(ap
, format
);
2776 buf
.writestring("// Ignored ");
2777 buf
.vprintf(format
, ap
);
2784 /// Writes a formatted message into `buf` if `printIgnored` is true
2785 /// and increments `ignoredCounter`
2787 private void ignored(const char* format
, ...) nothrow
2789 this.ignoredCounter
++;
2791 import core
.stdc
.stdarg
;
2796 va_start(ap
, format
);
2797 buf
.writestring("// Ignored ");
2798 buf
.vprintf(format
, 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)
2812 * Returns: whether `sym` should be emitted
2814 private bool shouldEmit(AST
.Dsymbol sym
)
2816 import dmd
.aggregate
: ClassKind
;
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())
2827 // Matching linkage (except extern(C) classes which don't make sense)
2828 if (linkage
== LINK
.cpp ||
(linkage
== LINK
.c
&& !sym
.isClassDeclaration()))
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
;
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.
2854 * Returns: whether `sym` should be emitted
2856 private bool shouldEmitAndMarkVisited(AST
.Dsymbol sym
)
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
))
2870 // Template *instances* should not be emitted, forward to the declaration
2871 if (auto ti
= sym
.isInstantiated())
2873 auto td
= findTemplateDeclaration(ti
);
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());
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
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());
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
));
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))
2933 // Already created a fwd-declaration?
2934 if (check
in forwarded
)
2936 forwarded
[check
] = true;
2938 // Print template<...>
2943 printTemplateParams(td
);
2947 // Determine the kind of symbol that is forwared: struct, ...
2950 if (auto ad
= sym
.isAggregateDeclaration())
2952 // Look for extern(C++, class) <some aggregate>
2953 if (ad
.cppmangle
== CPPMANGLE
.def
)
2955 else if (ad
.cppmangle
== CPPMANGLE
.asStruct
)
2962 // Only called from enumToBuffer, so should always be emitted as an actual enum
2963 kind
= "enum class";
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.
2980 * mustInclude = whether sym may not be forward declared
2982 private void writeFullName(AST
.Dsymbol sym
, const bool mustInclude
= false)
2986 assert(sym
.ident
, sym
.toString());
2987 // Should never be called directly with a TI, only onemember
2988 assert(!sym
.isTemplateInstance(), sym
.toString());
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
)
3009 par
= par
.toParent();
3013 AST
.TemplateInstance ti
;
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("::");
3037 // Cannot forward the symbol when called recursively
3038 // for a nested symbol
3042 ensureDeclared(sym
);
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
;
3061 /// Namespace for identifiers used to represent special enums in C++
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
;
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
3093 __gshared
bool initialized
;
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
)
3144 const name
= ident
.toString();
3159 return "special operator in C++";
3165 case "dynamic_cast":
3173 case "reinterpret_cast":
3182 return "keyword in C++";
3184 // Common macros imported by this header
3188 return "default macro in C++";
3199 case "static_assert":
3200 case "thread_local":
3202 if (global
.params
.cplusplus
>= CppStdRevision
.cpp11
)
3203 return "keyword in C++11";
3210 // Concepts-related keywords
3213 // Coroutines-related keywords
3217 if (global
.params
.cplusplus
>= CppStdRevision
.cpp20
)
3218 return "keyword in C++20";
3225 //case "_Complex": // handled above in C++
3229 case "_Static_assert":
3230 case "_Thread_local":
3233 //case "__...": handled in default case below
3234 return "Keyword in C";
3237 // Identifiers starting with __ are reserved
3238 if (name
.length
>= 2 && name
[0..2] == "__")
3239 return "reserved identifier in C++";
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
)
3252 auto par
= sym
.toParent();
3253 if (!par || par
.isModule())
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())
3265 if (auto ts
= t
.isTypeStruct())
3267 if (auto te
= t
.isTypeEnum())
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
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
))
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
)
3295 // Manually check the members if present
3296 auto sds
= sym
.isScopeDsymbol();
3297 if (!sds ||
!sds
.members
)
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
)
3308 // Look inside of private:, ...
3309 if (auto ad
= mem
.isAttribDeclaration())
3311 if (auto s
= search(ad
.decl
, name
))
3318 return search(sds
.members
, name
);
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
~ `());`;