-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathdtoh.d
3384 lines (2943 loc) · 102 KB
/
dtoh.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This module contains the implementation of the C++ header generation available through
* the command line switch -Hc.
*
* Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dtohd, _dtoh.d)
* Documentation: https://dlang.org/phobos/dmd_dtoh.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dtoh.d
*/
module dmd.dtoh;
import core.stdc.stdio;
import core.stdc.string;
import core.stdc.ctype;
import dmd.astcodegen;
import dmd.astenums;
import dmd.arraytypes;
import dmd.attrib;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.errors;
import dmd.globals;
import dmd.hdrgen;
import dmd.id;
import dmd.identifier;
import dmd.location;
import dmd.root.filename;
import dmd.visitor;
import dmd.tokens;
import dmd.typesem;
import dmd.common.outbuffer;
import dmd.utils;
//debug = Debug_DtoH;
// Generate asserts to validate the header
//debug = Debug_DtoH_Checks;
/**
* Generates a C++ header containing bindings for all `extern(C[++])` declarations
* found in the supplied modules.
*
* Params:
* ms = the modules
*
* Notes:
* - the header is written to `<global.params.cxxhdrdir>/<global.params.cxxhdrfile>`
* or `stdout` if no explicit file was specified
* - bindings conform to the C++ standard defined in `global.params.cplusplus`
* - ignored declarations are mentioned in a comment if `global.params.doCxxHdrGeneration`
* is set to `CxxHeaderMode.verbose`
*/
void genCppHdrFiles(ref Modules ms)
{
initialize();
OutBuffer fwd;
OutBuffer done;
OutBuffer decl;
// enable indent by spaces on buffers
fwd.doindent = true;
fwd.spaces = true;
decl.doindent = true;
decl.spaces = true;
scope v = new ToCppBuffer(&fwd, &done, &decl);
// Conditionally include another buffer for sanity checks
debug (Debug_DtoH_Checks)
{
OutBuffer check;
check.doindent = true;
check.spaces = true;
v.checkbuf = ✓
}
OutBuffer buf;
buf.doindent = true;
buf.spaces = true;
foreach (m; ms)
m.accept(v);
if (global.params.cxxhdr.fullOutput)
buf.printf("// Automatically generated by %s Compiler v%d", global.compileEnv.vendor.ptr, global.versionNumber());
else
buf.printf("// Automatically generated by %s Compiler", global.compileEnv.vendor.ptr);
buf.writenl();
buf.writenl();
buf.writestringln("#pragma once");
buf.writenl();
hashInclude(buf, "<assert.h>");
hashInclude(buf, "<math.h>");
hashInclude(buf, "<stddef.h>");
hashInclude(buf, "<stdint.h>");
// buf.writestring(buf, "#include <stdio.h>\n");
// buf.writestring("#include <string.h>\n");
// Emit array compatibility because extern(C++) types may have slices
// as members (as opposed to function parameters)
if (v.hasDArray)
buf.writestring(`
#ifdef CUSTOM_D_ARRAY_TYPE
#define _d_dynamicArray CUSTOM_D_ARRAY_TYPE
#else
/// Represents a D [] array
template<typename T>
struct _d_dynamicArray final
{
size_t length;
T *ptr;
_d_dynamicArray() : length(0), ptr(NULL) { }
_d_dynamicArray(size_t length_in, T *ptr_in)
: length(length_in), ptr(ptr_in) { }
T& operator[](const size_t idx) {
assert(idx < length);
return ptr[idx];
}
const T& operator[](const size_t idx) const {
assert(idx < length);
return ptr[idx];
}
};
#endif
`);
if (v.hasExternSystem)
buf.writestring(`
#ifndef _WIN32
#define EXTERN_SYSTEM_AFTER __stdcall
#define EXTERN_SYSTEM_BEFORE
#else
#define EXTERN_SYSTEM_AFTER
#define EXTERN_SYSTEM_BEFORE extern "C"
#endif
`);
if (v.hasReal)
{
hashIf(buf, "!defined(_d_real)");
{
hashDefine(buf, "_d_real long double");
}
hashEndIf(buf);
}
buf.writenl();
// buf.writestringln("// fwd:");
buf.write(&fwd);
if (fwd.length > 0)
buf.writenl();
// buf.writestringln("// done:");
buf.write(&done);
// buf.writestringln("// decl:");
buf.write(&decl);
debug (Debug_DtoH_Checks)
{
// buf.writestringln("// check:");
buf.writestring(`
#if OFFSETS
template <class T>
size_t getSlotNumber(int dummy, ...)
{
T c;
va_list ap;
va_start(ap, dummy);
void *f = va_arg(ap, void*);
for (size_t i = 0; ; i++)
{
if ( (*(void***)&c)[i] == f)
return i;
}
va_end(ap);
}
void testOffsets()
{
`);
buf.write(&check);
buf.writestring(`
}
#endif
`);
}
// prevent trailing newlines
version (Windows)
while (buf.length >= 4 && buf[$-4..$] == "\r\n\r\n")
buf.remove(buf.length - 2, 2);
else
while (buf.length >= 2 && buf[$-2..$] == "\n\n")
buf.remove(buf.length - 1, 1);
if (global.params.cxxhdr.name is null)
{
// Write to stdout; assume it succeeds
size_t n = fwrite(buf[].ptr, 1, buf.length, stdout);
assert(n == buf.length); // keep gcc happy about return values
}
else
{
const(char)[] name = FileName.combine(global.params.cxxhdr.dir, global.params.cxxhdr.name);
if (!writeFile(Loc.initial, name, buf[]))
return fatal();
}
}
private:
/****************************************************
* Visitor that writes bindings for `extern(C[++]` declarations.
*/
extern(C++) final class ToCppBuffer : Visitor
{
alias visit = Visitor.visit;
public:
enum EnumKind
{
Int,
Numeric,
String,
Enum,
Other
}
/// Namespace providing the actual AST nodes
alias AST = ASTCodegen;
/// Visited nodes
bool[void*] visited;
/// Forward declared nodes (which might not be emitted yet)
bool[void*] forwarded;
/// Buffer for forward declarations
OutBuffer* fwdbuf;
/// Buffer for integrity checks
debug (Debug_DtoH_Checks) OutBuffer* checkbuf;
/// Buffer for declarations that must emitted before the currently
/// visited node but can't be forward declared (see `includeSymbol`)
OutBuffer* donebuf;
/// Default buffer for the currently visited declaration
OutBuffer* buf;
/// The generated header uses `real` emitted as `_d_real`?
bool hasReal = false;
/// The generated header has extern(System) functions,
/// which needs support macros in the header
bool hasExternSystem = false;
/// There are functions taking slices, which need a compatibility struct for C++
bool hasDArray = false;
/// The generated header should contain comments for skipped declarations?
const bool printIgnored;
/// State specific to the current context which depends
/// on the currently visited node and it's parents
static struct Context
{
/// Default linkage in the current scope (e.g. LINK.c inside `extern(C) { ... }`)
LINK linkage = LINK.d;
/// Enclosing class / struct / union
AST.AggregateDeclaration adparent;
/// Enclosing template declaration
AST.TemplateDeclaration tdparent;
/// Identifier of the currently visited `VarDeclaration`
/// (required to write variables of funtion pointers)
Identifier ident;
/// Original type of the currently visited declaration
AST.Type origType;
/// Last written visibility level applying to the current scope
AST.Visibility.Kind currentVisibility;
/// Currently applicable storage classes
AST.STC storageClass;
/// How many symbols were ignored
int ignoredCounter;
/// Currently visited types are required by another declaration
/// and hence must be emitted
bool mustEmit;
/// Processing a type that can be forward referenced
bool forwarding;
/// Inside of an anonymous struct/union (AnonDeclaration)
bool inAnonymousDecl;
}
/// Informations about the current context in the AST
Context context;
// Generates getter-setter methods to replace the use of alias this
// This should be replaced by a `static foreach` once the gdc tester
// gets upgraded to version 10 (to support `static foreach`).
private extern(D) static string generateMembers() @safe
{
string result = "";
foreach(member; __traits(allMembers, Context))
{
result ~= "ref auto " ~ member ~ "() { return context." ~ member ~ "; }\n";
}
return result;
}
mixin(generateMembers());
this(OutBuffer* fwdbuf, OutBuffer* donebuf, OutBuffer* buf) scope
{
this.fwdbuf = fwdbuf;
this.donebuf = donebuf;
this.buf = buf;
this.printIgnored = global.params.cxxhdr.fullOutput;
}
/**
* Emits `dsym` into `donebuf` s.t. it is declared before the currently
* visited symbol that written to `buf`.
*
* Temporarily clears `context` to behave as if it was visited normally.
*/
private void includeSymbol(AST.Dsymbol dsym)
{
debug (Debug_DtoH)
{
printf("[includeSymbol(AST.Dsymbol) enter] %s\n", dsym.toChars());
scope(exit) printf("[includeSymbol(AST.Dsymbol) exit] %s\n", dsym.toChars());
}
auto ptr = cast(void*) dsym in visited;
if (ptr && *ptr)
return;
// Temporary replacement for `buf` which is appended to `donebuf`
OutBuffer decl;
decl.doindent = true;
decl.spaces = true;
scope (exit) donebuf.write(&decl);
auto ctxStash = this.context;
auto bufStash = this.buf;
this.context = Context.init;
this.buf = &decl;
this.mustEmit = true;
dsym.accept(this);
this.context = ctxStash;
this.buf = bufStash;
}
/// Determines what kind of enum `type` is (see `EnumKind`)
private EnumKind getEnumKind(AST.Type type)
{
if (type) switch (type.ty)
{
case AST.Tint32:
return EnumKind.Int;
case AST.Tbool,
AST.Tchar, AST.Twchar, AST.Tdchar,
AST.Tint8, AST.Tuns8,
AST.Tint16, AST.Tuns16,
AST.Tuns32,
AST.Tint64, AST.Tuns64:
return EnumKind.Numeric;
case AST.Tarray:
if (type.isString())
return EnumKind.String;
break;
case AST.Tenum:
return EnumKind.Enum;
default:
break;
}
return EnumKind.Other;
}
/// Determines the type used to represent `type` in C++.
/// Returns: `const [w,d]char*` for `[w,d]string` or `type`
private AST.Type determineEnumType(AST.Type type)
{
if (auto arr = type.isTypeDArray())
{
switch (arr.next.ty)
{
case AST.Tchar: return AST.Type.tchar.constOf.pointerTo;
case AST.Twchar: return AST.Type.twchar.constOf.pointerTo;
case AST.Tdchar: return AST.Type.tdchar.constOf.pointerTo;
default: break;
}
}
return type;
}
/// Writes a final `;` and insert an empty line outside of aggregates
private void writeDeclEnd() @safe
{
buf.writestringln(";");
if (!adparent)
buf.writenl();
}
/// Writes the corresponding access specifier if necessary
private void writeProtection(const AST.Visibility.Kind kind)
{
// Don't write visibility for global declarations
if (!adparent || inAnonymousDecl)
return;
string token;
switch(kind) with(AST.Visibility.Kind)
{
case none, private_:
if (this.currentVisibility == AST.Visibility.Kind.private_)
return;
this.currentVisibility = AST.Visibility.Kind.private_;
token = "private:";
break;
case package_, protected_:
if (this.currentVisibility == AST.Visibility.Kind.protected_)
return;
this.currentVisibility = AST.Visibility.Kind.protected_;
token = "protected:";
break;
case undefined, public_, export_:
if (this.currentVisibility == AST.Visibility.Kind.public_)
return;
this.currentVisibility = AST.Visibility.Kind.public_;
token = "public:";
break;
default:
printf("Unexpected visibility: %d!\n", kind);
assert(0);
}
buf.level--;
buf.writestringln(token);
buf.level++;
}
/**
* Writes an identifier into `buf` and checks for reserved identifiers. The
* parameter `canFix` determines how this function handles C++ keywords:
*
* `false` => Raise a warning and print the identifier as-is
* `true` => Append an underscore to the identifier
*
* Params:
* s = the symbol denoting the identifier
* canFixup = whether the identifier may be changed without affecting
* binary compatibility
*/
private void writeIdentifier(const AST.Dsymbol s, const bool canFix = false)
{
if (const mn = getMangleOverride(s))
return buf.writestring(mn);
writeIdentifier(s.ident, s.loc, s.kind(), canFix);
}
/** Overload of `writeIdentifier` used for all AST nodes not descending from Dsymbol **/
private void writeIdentifier(const Identifier ident, const Loc loc, const char* kind, const bool canFix = false)
{
bool needsFix;
void warnCxxCompat(const(char)* reason)
{
if (canFix)
{
needsFix = true;
return;
}
__gshared bool warned = false;
warning(loc, "%s `%s` is a %s", kind, ident.toChars(), reason);
if (!warned)
{
warningSupplemental(loc, "The generated C++ header will contain " ~
"identifiers that are keywords in C++");
warned = true;
}
}
if (global.params.useWarnings != DiagnosticReporting.off || canFix)
{
// Warn about identifiers that are keywords in C++.
if (auto kc = keywordClass(ident))
warnCxxCompat(kc);
}
buf.writestring(ident.toString());
if (needsFix)
buf.writeByte('_');
}
/// Checks whether `t` is a type that can be exported to C++
private bool isSupportedType(AST.Type t)
{
if (!t)
{
assert(tdparent);
return true;
}
switch (t.ty)
{
// Nested types
case AST.Tarray:
case AST.Tsarray:
case AST.Tpointer:
case AST.Treference:
case AST.Tdelegate:
return isSupportedType((cast(AST.TypeNext) t).next);
// Function pointers
case AST.Tfunction:
{
auto tf = cast(AST.TypeFunction) t;
if (!isSupportedType(tf.next))
return false;
foreach (_, param; tf.parameterList)
{
if (!isSupportedType(param.type))
return false;
}
return true;
}
// Noreturn has a different mangling
case AST.Tnoreturn:
// _Imaginary is C only.
case AST.Timaginary32:
case AST.Timaginary64:
case AST.Timaginary80:
return false;
default:
return true;
}
}
override void visit(AST.Dsymbol s)
{
debug (Debug_DtoH)
{
mixin(traceVisit!s);
import dmd.asttypename;
printf("[AST.Dsymbol enter] %s\n", s.astTypeName().ptr);
}
}
override void visit(AST.Import i)
{
debug (Debug_DtoH) mixin(traceVisit!i);
/// Writes `using <alias_> = <sym.ident>` into `buf`
const(char*) writeImport(AST.Dsymbol sym, const Identifier alias_)
{
/// `using` was introduced in C++ 11 and only works for types...
if (global.params.cplusplus < CppStdRevision.cpp11)
return "requires C++11";
if (auto ad = sym.isAliasDeclaration())
{
sym = ad.toAlias();
ad = sym.isAliasDeclaration();
// Might be an alias to a basic type
if (ad && !ad.aliassym && ad.type)
goto Emit;
}
// Restricted to types and other aliases
if (!sym.isScopeDsymbol() && !sym.isAggregateDeclaration())
return "only supports types";
// Write `using <alias_> = `<sym>`
Emit:
buf.writestring("using ");
writeIdentifier(alias_, i.loc, "renamed import");
buf.writestring(" = ");
// Start at module scope to avoid collisions with local symbols
if (this.context.adparent)
buf.writestring("::");
buf.writestring(sym.ident.toString());
writeDeclEnd();
return null;
}
// Only missing without semantic analysis
// FIXME: Templates need work due to missing parent & imported module
if (!i.parent)
{
assert(tdparent);
ignored("`%s` because it's inside of a template declaration", i.toChars());
return;
}
// Non-public imports don't create new symbols, include as needed
if (i.visibility.kind < AST.Visibility.Kind.public_)
return;
// Symbols from static imports should be emitted inline
if (i.isstatic)
return;
const isLocal = !i.parent.isModule();
// Need module for symbol lookup
assert(i.mod);
// Emit an alias for each public module member
if (isLocal && i.names.length == 0)
{
assert(i.mod.symtab);
// Sort alphabetically s.t. slight changes in semantic don't cause
// massive changes in the order of declarations
AST.Dsymbols entries;
entries.reserve(i.mod.symtab.length);
foreach (entry; i.mod.symtab.tab.asRange)
{
// Skip anonymous / invisible members
import dmd.access : symbolIsVisible;
if (!entry.key.isAnonymous() && symbolIsVisible(i, entry.value))
entries.push(entry.value);
}
// Seperate function because of a spurious dual-context deprecation
static int compare(const AST.Dsymbol* a, const AST.Dsymbol* b)
{
return strcmp(a.ident.toChars(), b.ident.toChars());
}
entries.sort!compare();
foreach (sym; entries)
{
includeSymbol(sym);
if (auto err = writeImport(sym, sym.ident))
ignored("public import for `%s` because `using` %s", sym.ident.toChars(), err);
}
return;
}
// Include all public imports and emit using declarations for each alias
foreach (const idx, name; i.names)
{
// Search the imported symbol
auto sym = i.mod.search(Loc.initial, name);
assert(sym); // Missing imports should error during semantic
includeSymbol(sym);
// Detect the assigned name for renamed import
auto alias_ = i.aliases[idx];
if (!alias_)
continue;
if (auto err = writeImport(sym, alias_))
ignored("renamed import `%s = %s` because `using` %s", alias_.toChars(), name.toChars(), err);
}
}
override void visit(AST.AttribDeclaration pd)
{
debug (Debug_DtoH) mixin(traceVisit!pd);
Dsymbols* decl = pd.include(null);
if (!decl)
return;
foreach (s; *decl)
{
if (adparent || s.visible().kind >= AST.Visibility.Kind.public_)
s.accept(this);
}
}
override void visit(AST.StorageClassDeclaration scd)
{
debug (Debug_DtoH) mixin(traceVisit!scd);
const stcStash = this.storageClass;
this.storageClass |= scd.stc;
visit(cast(AST.AttribDeclaration) scd);
this.storageClass = stcStash;
}
override void visit(AST.LinkDeclaration ld)
{
debug (Debug_DtoH) mixin(traceVisit!ld);
auto save = linkage;
linkage = ld.linkage;
visit(cast(AST.AttribDeclaration)ld);
linkage = save;
}
override void visit(AST.CPPMangleDeclaration md)
{
debug (Debug_DtoH) mixin(traceVisit!md);
const oldLinkage = this.linkage;
this.linkage = LINK.cpp;
visit(cast(AST.AttribDeclaration) md);
this.linkage = oldLinkage;
}
override void visit(AST.Module m)
{
debug (Debug_DtoH) mixin(traceVisit!m);
foreach (s; *m.members)
{
if (s.visible().kind < AST.Visibility.Kind.public_)
continue;
s.accept(this);
}
}
override void visit(AST.FuncDeclaration fd)
{
debug (Debug_DtoH) mixin(traceVisit!fd);
if (cast(void*)fd in visited)
return;
// printf("FuncDeclaration %s %s\n", fd.toPrettyChars(), fd.type.toChars());
visited[cast(void*)fd] = true;
// silently ignore non-user-defined destructors
if (fd.isGenerated && fd.isDtorDeclaration())
return;
// Note that tf might be null for templated (member) functions
auto tf = cast(AST.TypeFunction)fd.type;
if ((tf && (tf.linkage != LINK.c || adparent) && tf.linkage != LINK.cpp && tf.linkage != LINK.windows) || (!tf && fd.isPostBlitDeclaration()))
{
ignored("function %s because of linkage", fd.toPrettyChars());
return checkFunctionNeedsPlaceholder(fd);
}
if (fd.mangleOverride && tf && tf.linkage != LINK.c)
{
ignored("function %s because C++ doesn't support explicit mangling", fd.toPrettyChars());
return checkFunctionNeedsPlaceholder(fd);
}
if (!adparent && !fd.fbody)
{
ignored("function %s because it is extern", fd.toPrettyChars());
return;
}
if (fd.visibility.kind == AST.Visibility.Kind.none || fd.visibility.kind == AST.Visibility.Kind.private_)
{
ignored("function %s because it is private", fd.toPrettyChars());
return;
}
if (tf && !isSupportedType(tf.next))
{
ignored("function %s because its return type cannot be mapped to C++", fd.toPrettyChars());
return checkFunctionNeedsPlaceholder(fd);
}
if (tf) foreach (i, fparam; tf.parameterList)
{
if (!isSupportedType(fparam.type))
{
ignored("function %s because one of its parameters has type `%s` which cannot be mapped to C++",
fd.toPrettyChars(), fparam.type.toChars());
return checkFunctionNeedsPlaceholder(fd);
}
}
if (tf && tf.next)
{
// Ensure return type is declared before a function that returns that is declared.
if (auto sty = tf.next.isTypeStruct())
ensureDeclared(sty.sym);
//else if (auto cty = tf.next.isTypeClass())
// includeSymbol(cty.sym); // classes are returned by pointer only need to forward declare
//else if (auto ety = tf.next.isTypeEnum())
// ensureDeclared(ety.sym);
}
writeProtection(fd.visibility.kind);
if (fd._linkage == LINK.system)
{
hasExternSystem = true;
buf.writestring("EXTERN_SYSTEM_BEFORE ");
}
else if (tf && tf.linkage == LINK.c)
buf.writestring("extern \"C\" ");
else if (tf && tf.linkage == LINK.windows)
{
// __stdcall is printed after return type
}
else if (!adparent)
buf.writestring("extern ");
if (adparent && fd.isStatic())
buf.writestring("static ");
else if (adparent && (
// Virtual functions in non-templated classes
(fd.vtblIndex != -1 && !fd.isOverride()) ||
// Virtual functions in templated classes (fd.vtblIndex still -1)
(tdparent && adparent.isClassDeclaration() && !(this.storageClass & AST.STC.final_ || fd.isFinal))))
buf.writestring("virtual ");
debug (Debug_DtoH_Checks)
if (adparent && !tdparent)
{
auto s = adparent.search(Loc.initial, fd.ident);
auto cd = adparent.isClassDeclaration();
if (!(adparent.storage_class & AST.STC.abstract_) &&
!(cd && cd.isAbstract()) &&
s is fd && !fd.overnext)
{
const cn = adparent.ident.toChars();
const fn = fd.ident.toChars();
const vi = fd.vtblIndex;
checkbuf.printf("assert(getSlotNumber <%s>(0, &%s::%s) == %d);",
cn, cn, fn, vi);
checkbuf.writenl();
}
}
if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11)
writeProtection(AST.Visibility.Kind.private_);
funcToBuffer(tf, fd);
if (adparent)
{
if (tf && (tf.isConst() || tf.isImmutable()))
buf.writestring(" const");
if (global.params.cplusplus >= CppStdRevision.cpp11)
{
if (fd.vtblIndex != -1 && !(adparent.storage_class & AST.STC.final_) && fd.isFinalFunc())
buf.writestring(" final");
if (fd.isOverride())
buf.writestring(" override");
}
if (fd.isAbstract())
buf.writestring(" = 0");
else if (global.params.cplusplus >= CppStdRevision.cpp11 && fd.isDisabled())
buf.writestring(" = delete");
}
buf.writestringln(";");
if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11)
writeProtection(AST.Visibility.Kind.public_);
if (!adparent)
buf.writenl();
}
/++
+ Checks whether `fd` is a function that requires a dummy declaration
+ instead of simply emitting the declaration (because it would cause
+ ABI / behaviour issues). This includes:
+
+ - virtual functions to ensure proper vtable layout
+ - destructors that would break RAII
+/
private void checkFunctionNeedsPlaceholder(AST.FuncDeclaration fd)
{
// Omit redundant declarations - the slot was already
// reserved in the base class
if (fd.isVirtual() && fd.isIntroducing())
{
// Hide placeholders because they are not ABI compatible
writeProtection(AST.Visibility.Kind.private_);
__gshared int counter; // Ensure unique names in all cases
buf.printf("virtual void __vtable_slot_%u();", counter++);
buf.writenl();
}
else if (fd.isDtorDeclaration())
{
// Create inaccessible dtor to prevent code from keeping instances that
// need to be destroyed on the C++ side (but cannot call the dtor)
writeProtection(AST.Visibility.Kind.private_);
buf.writeByte('~');
buf.writestring(adparent.ident.toString());
buf.writestringln("();");
}
}
override void visit(AST.UnitTestDeclaration utd)
{
debug (Debug_DtoH) mixin(traceVisit!utd);
}
override void visit(AST.VarDeclaration vd)
{
debug (Debug_DtoH) mixin(traceVisit!vd);
if (!shouldEmitAndMarkVisited(vd))
return;
// Tuple field are expanded into multiple VarDeclarations
// (we'll visit them later)
if (vd.type && vd.type.isTypeTuple())
{
assert(vd.aliasTuple);
vd.toAlias().accept(this);
return;
}
if (vd.originalType && vd.type == AST.Type.tsize_t)
origType = vd.originalType;
scope(exit) origType = null;
if (!vd.alignment.isDefault() && !vd.alignment.isUnknown())
{
buf.printf("// Ignoring var %s alignment %d", vd.toChars(), vd.alignment.get());
buf.writenl();
}
// Determine the variable type which might be missing inside of
// template declarations. Infer the type from the initializer then
AST.Type type = vd.type;
if (!type)
{
assert(tdparent);
// Just a precaution, implicit type without initializer should be rejected
if (!vd._init)
return;
if (auto ei = vd._init.isExpInitializer())
type = ei.exp.type;
// Can happen if the expression needs further semantic
if (!type)
{
ignored("%s because the type could not be determined", vd.toPrettyChars());
return;
}
// Apply const/immutable to the inferred type
if (vd.storage_class & (AST.STC.const_ | AST.STC.immutable_))
type = type.constOf();
}
if (vd.storage_class & AST.STC.manifest)
{
EnumKind kind = getEnumKind(type);
if (vd.visibility.kind == AST.Visibility.Kind.none || vd.visibility.kind == AST.Visibility.Kind.private_) {
ignored("enum `%s` because it is `%s`.", vd.toPrettyChars(), AST.visibilityToChars(vd.visibility.kind));
return;
}
writeProtection(vd.visibility.kind);
final switch (kind)
{
case EnumKind.Int, EnumKind.Numeric:
// 'enum : type' is only available from C++-11 onwards.
if (global.params.cplusplus < CppStdRevision.cpp11)
goto case;
buf.writestring("enum : ");
determineEnumType(type).accept(this);
buf.writestring(" { ");
writeIdentifier(vd, true);
buf.writestring(" = ");
auto ie = AST.initializerToExpression(vd._init).isIntegerExp();
visitInteger(ie.toInteger(), type);
buf.writestring(" };");
break;