-
Notifications
You must be signed in to change notification settings - Fork 1
/
FileOutput.cs
2716 lines (2588 loc) · 123 KB
/
FileOutput.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace MetadataParser
{
// This entire class is very FB specific
// This is the main place you want to be changing things for different languages
// Search the code base for FB SPECIFIC as there are unavoidably a few others scattered around
//
// to do
class OutputCreator
{
private TypeCollectionResults collectionResults;
private HashSet<string> fbKeywords;
public OutputCreator(TypeCollectionResults typeCollection)
{
fbKeywords = GetFBKeywords();
collectionResults = typeCollection;
}
private HashSet<string> GetFBKeywords()
{
// fb keywords or built-ins that might be function parameter names or typedef names
// which would cause compilation to fail if they appear in those places
string[] keywords =
{
"len", "data", "true", "false", "object", "extends", "type", "union", "error", "err",
"output", "dim", "redim", "as", "read", "declare", "name", "next", "step", "enum",
"class", "public", "protected", "private", "do", "loop", "property", "end", "select", "new",
"delete", "string", "mod", "this", "import", "beep", "rgb", "continue", "out", "in", "call",
"lock", "unlock", "export", "namespace", "base", "restore", "local", "is", "peek", "poke", "swap"
};
return new HashSet<string>(keywords);
}
public void WriteNamespaceHeaders(App.OptionSet options, Dictionary<string, Dictionary<string, string>> injections)
{
string baseDir = options.outputDirectory;
Directory.CreateDirectory(baseDir);
string defDirX86 = Path.Combine(baseDir, "DefFilesX86");
string defDirX64 = Path.Combine(baseDir, "DefFilesX64");
Directory.CreateDirectory(defDirX86);
Directory.CreateDirectory(defDirX64);
if (options.generateGuidFiles)
{
string guidDir = Path.Combine(baseDir, FileOutput.GUID_DIR);
Directory.CreateDirectory(guidDir);
string pkeyDir = Path.Combine(baseDir, FileOutput.PKEY_DIR);
Directory.CreateDirectory(pkeyDir);
}
Dictionary<string, string> nullInjections = new Dictionary<string, string>();
DefFileMapping defMap = new DefFileMapping();
foreach(NamespaceContent ns in collectionResults.Contents.Values)
{
RawTypeEntries nsTypes = ns.TypeEntries;
TypeOrderer orderer = new TypeOrderer(ns.Name, nsTypes);
List<TypeOrderer.AddedObject> inOrderList = orderer.MakeOrderedList(nsTypes);
// if we've moved all things from this namespace elsewhere
// there might not be anything in this namespace any more
if(inOrderList.Count == 0)
{
Console.WriteLine("After name fixes, namespace '{0}' is empty. No file generated", ns.Name);
continue;
}
Dictionary<string, string> nsInjections;
if(!injections.TryGetValue(ns.Name, out nsInjections))
{
nsInjections = nullInjections;
}
Console.WriteLine("Outputting {0}", ns.Name);
using (FileOutput file = new FileOutput(collectionResults.TypeRegistry, ns, fbKeywords, nsInjections, options, defMap))
{
Trace.WriteLine("Outputting {0}", ns.Name);
foreach(TypeOrderer.AddedObject obj in inOrderList)
{
file.Output(obj);
}
}
}
Console.WriteLine("Outputting defs to {0}/{1}", defDirX86, defDirX64);
defMap.WriteToDirectory(defDirX86, defDirX64);
}
}
class DefFileCreator
{
private StringBuilder defContentsX86;
private StringBuilder defContentsX64;
private string dll;
private static readonly string nl = Environment.NewLine;
public DefFileCreator(string dllName)
{
string header = String.Format(
"; Def file autogenerated by FBWindowsHeaderGen on {0}{2}{2}" +
"LIBRARY {1}{2}" +
"EXPORTS{2}",
DateTime.UtcNow.ToString("O"),
dllName,
nl
);
dll = dllName;
defContentsX86 = new StringBuilder(header, 2048);
defContentsX64 = new StringBuilder(header, 2048);
}
public void AddExport(string funcName, int argSize, bool stdcall)
{
const string NameOnlyFormat = "{0}{2}";
defContentsX86.AppendFormat(NameOnlyFormat, funcName, argSize, nl);
defContentsX64.AppendFormat(NameOnlyFormat, funcName, argSize, nl);
if (stdcall)
{
const string StdcallAliasFormat = "{0}@{1}={2}{3}";
defContentsX86.AppendFormat(StdcallAliasFormat, funcName, argSize, funcName, nl);
}
}
public void WriteToFile(string x86File, string x64File)
{
File.WriteAllText(x86File, defContentsX86.ToString());
File.WriteAllText(x64File, defContentsX64.ToString());
}
}
class DefFileMapping
{
private Dictionary<string, DefFileCreator> defFiles;
public DefFileMapping()
{
defFiles = new Dictionary<string, DefFileCreator>();
}
public void AddExport(string dllName, string functionName, int argSize, bool stdcall)
{
DefFileCreator creator;
if(!defFiles.TryGetValue(dllName, out creator))
{
creator = new DefFileCreator(dllName);
defFiles.Add(dllName, creator);
}
creator.AddExport(functionName, argSize, stdcall);
}
public void WriteToDirectory(string x86Dir, string x64Dir)
{
foreach (KeyValuePair<string, DefFileCreator> entry in defFiles)
{
string defName = entry.Key + ".def";
string outFileX64 = Path.Combine(x64Dir, defName);
string outFileX86 = Path.Combine(x86Dir, defName);
entry.Value.WriteToFile(outFileX86, outFileX64);
}
}
}
class ForwardDeclarationManager
{
public struct ForwardedType
{
public SimpleTypeHandleInfo BaseType { get; init; }
public bool IsHandle { get; init; }
public ForwardedType(SimpleTypeHandleInfo baseT, bool isAHandle)
{
BaseType = baseT;
IsHandle = isAHandle;
}
public void Format(StringBuilder output, SimpleTypeHandleInfo originalType)
{
if (IsHandle)
{
output.AppendFormat("Type {0} As {1}{2}", originalType, BaseType, Environment.NewLine);
}
else
{
output.AppendFormat("Type {0} As {1}{2}", BaseType, originalType, Environment.NewLine);
}
}
}
public struct ForwardDeclaration
{
// this is the equivalent of the input, so it contains the same number of ptr levels etc
public SimpleTypeHandleInfo Equivalent { get; init; }
// the base type without any ptr levels
public ForwardedType BaseType { get; init; }
public ForwardDeclaration(SimpleTypeHandleInfo equiv, SimpleTypeHandleInfo baseT, bool isHandleType)
{
Equivalent = equiv;
BaseType = new ForwardedType(baseT, isHandleType);
}
}
private Dictionary<string, ForwardedType> forwardDeclaredTypes;
public ForwardDeclarationManager()
{
forwardDeclaredTypes = new Dictionary<string, ForwardedType>();
}
public ForwardedType? Lookup(SimpleTypeHandleInfo type)
{
Debug.Assert(PointerTypeHandleInfo.StripAllPointers(type).Stripped == type, "Type passed should be the pointer stripped type");
ForwardedType forwardedType;
return forwardDeclaredTypes.TryGetValue(type.ToString(), out forwardedType) ? forwardedType : null;
}
public void ConcreteDeclaration(SimpleTypeHandleInfo typeToConcrete)
{
string typeName = typeToConcrete.ToString();
ForwardedType concreted = new ForwardedType(typeToConcrete, false);
if (!forwardDeclaredTypes.TryAdd(typeName, concreted))
{
forwardDeclaredTypes[typeName] = concreted;
}
}
public void Add(SimpleTypeHandleInfo realType, ForwardedType forwardedName)
{
forwardDeclaredTypes.Add(realType.ToString(), forwardedName);
}
public void FormatAndAdd(StringBuilder output, SimpleTypeHandleInfo origType, ForwardedType forwarded)
{
Debug.Assert(PointerTypeHandleInfo.StripAllPointers(origType).Stripped == origType, "Type passed should be the stripped pointer type");
if (Lookup(origType) == null)
{
forwarded.Format(output, origType);
Add(origType, forwarded);
}
}
public ForwardDeclaration CreateDeclForHandle(SimpleTypeHandleInfo handleType, SimpleTypeHandleInfo baseType)
{
return new ForwardDeclaration(handleType, baseType, true);
}
public ForwardDeclaration CreateDecl(SimpleTypeHandleInfo equivalent, SimpleTypeHandleInfo baseType)
{
return new ForwardDeclaration(equivalent, baseType, false);
}
}
class FileOutput : IDisposable
{
class OutputStreams
{
public StringBuilder Main { get; init; }
public StringBuilder AnsiDefs { get; init; }
public StringBuilder UnicodeDefs { get; init; }
public StringBuilder RaiiWrappers { get; init; }
public StringBuilder Overloads { get; init; }
public OutputStreams(int bufSize)
{
Main = new StringBuilder(bufSize);
Overloads = new StringBuilder(bufSize);
AnsiDefs = new StringBuilder(bufSize / 8);
UnicodeDefs = new StringBuilder(bufSize / 8);
RaiiWrappers = new StringBuilder(bufSize / 16);
}
public void Reset(bool includeMain)
{
AnsiDefs.Length = UnicodeDefs.Length = RaiiWrappers.Length = 0;
if (includeMain)
{
Main.Length = 0;
}
}
public bool HasAnyContent()
{
return (Main.Length + AnsiDefs.Length + UnicodeDefs.Length + RaiiWrappers.Length) > 0;
}
}
private OutputStreams outputStreams;
private HashSet<string> headers;
private HashSet<string> fbKeywords;
private ForwardDeclarationManager forwardDecls;
private GlobalTypeRegistry typeRegistry;
private Dictionary<string, string> injections;
private App.OptionSet options;
private NamespaceContent ns;
private string guidDir;
private string propkeyDir;
private DefFileMapping defFiles;
private HashSet<string> raiiWrappersCreated;
private bool ForceForwardDecls { get; set; }
private readonly static CustomAttributeValues dummyAttrVals = new CustomAttributeValues();
private readonly static string nl = Environment.NewLine;
const string INDENT = " ";
const string AUTOFREE_WRAP_SUFFIX = "Wrap";
const string FB_KEYWORD_PREFIX = "__";
internal const string GUID_DIR = "GuidFiles";
internal const string PKEY_DIR = "PropKeyFiles";
const string FORWARD_DECLARE_SUFFIX = "_fwd_";
const string HANDLE_TYPE_SUFFIX = "__";
const string x64Guard = "defined(__FB_64BIT__)";
const string x86Guard = "not defined(__FB_64BIT__)";
const string HEADER_INSERT_FORMAT = "End Extern{0}#include once \"{1}.bi\"{0}Extern \"Windows\"{0}";
private readonly int NSPrefixLength;
const SupportedArchitecture FB_ARCHS = SupportedArchitecture.X86 | SupportedArchitecture.X64;
class IfDefGuard : IDisposable
{
private StringBuilder content;
private string guardText;
private static readonly string nl = Environment.NewLine;
public IfDefGuard(StringBuilder sb, string guard)
{
content = sb;
guardText = guard;
if (guardText.Length > 0)
{
content.AppendFormat("#If {0}{1}", guard, nl);
}
}
public void Dispose()
{
if (guardText.Length > 0)
{
content.AppendFormat("#Endif '' {0}{1}{1}", guardText, nl);
}
}
}
public FileOutput(
GlobalTypeRegistry typedefs,
NamespaceContent nsContent,
HashSet<string> keywords,
Dictionary<string, string> nsInjections,
App.OptionSet optionSet,
DefFileMapping defMap
)
{
const int oneMeg = 1024 * 1024;
outputStreams = new OutputStreams(oneMeg);
headers = new HashSet<string>(16);
raiiWrappersCreated = new HashSet<string>(16);
forwardDecls = new ForwardDeclarationManager();
ns = nsContent;
fbKeywords = keywords;
typeRegistry = typedefs;
injections = nsInjections;
options = optionSet;
ForceForwardDecls = false;
NSPrefixLength = "windows.win32.".Length;
defFiles = defMap;
if (options.generateGuidFiles)
{
guidDir = Path.Combine(options.outputDirectory, GUID_DIR);
propkeyDir = Path.Combine(options.outputDirectory, PKEY_DIR);
}
}
//private IfDefGuard GetArchOutput(CustomAttributeValues attrVals)
//{
// string guard;
// if (attrVals == null || (attrVals.supportedArch == SupportedArchitecture.None))
// {
// guard = String.Empty;
// }
// else
// {
// SupportedArchitecture arch = attrVals.supportedArch;
// if (((arch & SupportedArchitecture.All) == FB_ARCHS))
// {
// guard = String.Empty;
// }
// else if (arch == SupportedArchitecture.X86)
// {
// guard = x86Guard;
// }
// else if (arch == SupportedArchitecture.ARM64)
// {
// guard = null;
// }
// else
// {
// guard = x64Guard;
// }
// }
// return guard == null ? null : new IfDefGuard(guard == String.Empty ? null : outputStreams.Main, guard);
//}
private string GetArchIfdef(CustomAttributeValues attrVals)
{
string guard;
if (attrVals == null || (attrVals.supportedArch == SupportedArchitecture.None))
{
guard = String.Empty;
}
else
{
SupportedArchitecture arch = attrVals.supportedArch;
if ((arch & SupportedArchitecture.All) == FB_ARCHS)
{
guard = String.Empty;
}
else if((arch & SupportedArchitecture.X64) != 0)
{
guard = x64Guard;
}
else if ((arch & SupportedArchitecture.X86) != 0)
{
guard = x86Guard;
}
else // if (arch == SupportedArchitecture.ARM64)
{
guard = null;
}
}
return guard;
}
private void OutputInjectionType(StreamWriter sw, string injType)
{
string injText;
if (injections.TryGetValue(injType, out injText))
{
sw.WriteLine(injText);
}
}
public void Dispose()
{
headers.Remove(ns.Name);
MergeStreams();
string fileName = ns.Name.Remove(0, "windows.win32.".Length);
string outputFile = Path.Combine(options.outputDirectory, fileName + ".bi");
using (StreamWriter sw = new StreamWriter(outputFile))
{
string nsFBName = ns.Name.Replace(".", "_");
sw.WriteLine("'' Autogenerated FB header by FBWindowsHeaderGen on {0}{1}", DateTime.UtcNow.ToString("O"), nl);
sw.WriteLine("#Ifndef {0}{1}#define {0}{1}{1}", nsFBName, nl);
//foreach (string header in headers)
//{
// sw.WriteLine("#include once \"{0}.bi\"", header);
//}
sw.WriteLine();
sw.WriteLine("Extern \"Windows\"");
sw.WriteLine(outputStreams.Main.ToString());
OutputInjectionType(sw, "enums");
OutputInjectionType(sw, "structs");
OutputInjectionType(sw, "constants");
OutputInjectionType(sw, "functions");
OutputInjectionType(sw, "functionptrs");
OutputInjectionType(sw, "interfaces");
sw.WriteLine("End Extern '' \"Windows\"" + nl);
if (outputStreams.Overloads.Length > 0)
{
sw.WriteLine(outputStreams.Overloads.ToString());
}
sw.WriteLine("#EndIf '' " + nsFBName);
}
}
private void MergeStreams()
{
StringBuilder mainStream = outputStreams.Main;
OutputStreams[] builders = { outputStreams };
foreach (OutputStreams aob in builders)
{
if (aob.UnicodeDefs.Length > 0)
{
mainStream.AppendLine("#Ifdef UNICODE");
mainStream.AppendLine(aob.UnicodeDefs.ToString());
mainStream.AppendLine("#Endif '' UNICODE");
}
if (aob.AnsiDefs.Length > 0)
{
mainStream.AppendLine("#Ifndef UNICODE");
mainStream.AppendLine(aob.AnsiDefs.ToString());
mainStream.AppendLine("#Endif '' not UNICODE");
}
if (aob.RaiiWrappers.Length > 0)
{
mainStream.AppendLine(aob.RaiiWrappers.ToString());
}
}
}
public void Output(TypeOrderer.AddedObject addedObj)
{
ForceForwardDecls = addedObj.ForceForwardDeclares;
switch (addedObj.ObjType)
{
case RawTypeEntries.ObjectType.Constant: OutputConstant((ConstantValue)addedObj.TheObject); break;
case RawTypeEntries.ObjectType.Function: OutputFunction((FunctionType)addedObj.TheObject); break;
case RawTypeEntries.ObjectType.Struct: OutputStruct(null, null, null, (StructType<VarType>)addedObj.TheObject, options.niceWrappers, String.Empty, null, false); break;
case RawTypeEntries.ObjectType.Interface: OutputInterface((StructType<FunctionType>)addedObj.TheObject); break;
case RawTypeEntries.ObjectType.FunctionPointer: OutputFunctionPtr((FunctionPointerType)addedObj.TheObject); break;
case RawTypeEntries.ObjectType.Enum: OutputEnum((StructType<ConstantValue>)addedObj.TheObject); break;
}
}
//private void ResetFile()
//{
// headers.Clear();
// allArchContent.Reset(true);
//}
//private void OutputStructs(List<StructType<VarType>> structs, bool niceWrappers, string indent, string guidDir)
//{
// Dictionary<string, StringBuilder> unseenTypes = new Dictionary<string, StringBuilder>();
// foreach (StructType<VarType> structType in structs)
// {
// OutputStruct(structType, niceWrappers, indent, guidDir, false, unseenTypes);
// }
//}
private void OutputStruct(
StringBuilder outputLoc,
StringBuilder forwardDeclOutput,
StringBuilder headersOutput,
StructType<VarType> structType,
bool niceWrappers,
string indent,
HashSet<string> memberNames,
bool forceFullType
)
{
string memberIndent = indent + INDENT;
CustomAttributeValues attrVals = structType.AttributeValues ?? dummyAttrVals;
string archIfdef = GetArchIfdef(attrVals);
if (archIfdef == null) return;
StringBuilder content = outputLoc ?? outputStreams.Main;
string structName = MangleFBKeyword(structType.Name);
PrintTypeCommentPreamble(content, structName, attrVals);
bool innerType = (memberNames != null);
if (attrVals.guid.HasValue)
{
string guidName;
if (!(structName.StartsWith("CLSID") || structName.StartsWith("IID") || structName.StartsWith("GUID") || structName.StartsWith("SID")))
{
guidName = "CLSID_" + structName;
}
else
{
guidName = structName;
}
if (!String.IsNullOrEmpty(guidDir))
{
OutputGuidFile(guidDir, guidName, attrVals.guid.Value);
}
// this is where GUID is. we could lookup the guid type but since that means
// we have to type out the namespace and typename to find it, might as well just type it out
// to the file
if (headers.Add("windows.win32.foundation"))
{
content.AppendFormat(HEADER_INSERT_FORMAT, nl, "foundation");
}
content.AppendFormat("Extern {0} As Const GUID{1}", guidName, nl);
// some of these are the metadata translations of things like:
// class DECLSPEC_UUID("00021401-0000-0000-C000-000000000046")
// ShellLink;
// where the entry only exists to hang the coclass guid off
// in those cases, there's no point going through the other contortions
// just move on to the next one
if (structType.Fields.Count == 0)
{
return;
}
}
string strType;
if (structName.EndsWith("Union") || ((structType.TypeAttributes & TypeAttributes.ExplicitLayout) != 0))
{
strType = "Union";
}
else
{
strType = "Type";
}
List<VarType> structContents = structType.Fields;
// there are some inner types / anonymous unions that have the required data to generate autosizing constructors
// but in FB, anonymous unions can't have constructors
bool suppressInitWrap = innerType;
StringBuilder structBuffer = new StringBuilder();
StringBuilder forwardDeclarations = forwardDeclOutput ?? new StringBuilder();
StringBuilder headersOut = headersOutput ?? new StringBuilder();
// AFAICT These empty types are restricted to the GdiPlus object types like GpGraphics, GpImage
// Freebasic doesn't like empty types, so like handles, we fudge in a member so that
// they are unique types (instead of just making them Any Ptrs) so that can't be accidentally passed to each others functions
if (structContents.Count == 0)
{
Debug.Assert(structName.StartsWith("Gp"), "What is this type if not GdiPlus? Does this work for it?");
structContents.Add(new VarType("__unused", dummyAttrVals, new PrimitiveTypeHandleInfo(System.Reflection.Metadata.PrimitiveTypeCode.UInt32), FieldAttributes.Public));
}
// typedefs aren't really a type, just a wrapper for the real type
if (attrVals.nativeTypedef)
{
Debug.Assert(structContents.Count == 1, "Native typedef had more than 1 internal field!?");
SimpleTypeHandleInfo asType = structContents[0].ParamType;
// to increase type safety like in the Windows headers, instead of all the handles just been
// typedefs to void* as they are in the metadata (and thus freely assignable to each other),
// we create empty structs of each type and make the handle types pointers to those
// (so you can't assign a HWND to a HANDLE)
if (IsWinHandleType(structName, asType, typeRegistry))
{
OutputWindowsHandle(structBuffer, structName);
}
else
{
structBuffer.AppendFormat("{0}{1} {2} As {3}{4}", indent, strType, structName, MangleFBKeyword(asType.ToString()), nl);
}
AddHeaderForType(asType, headersOutput);
}
else
{
// Freebasic can handle anonymous inner types, so we take advantage of that
// unfortunatly, the metadata defines the anonymous types first, and then places fields of them
// at the correct offset. To do it properly, we need to hold off defining the anonymous structs and unions
// until the correct offset in the type
string packingSpace = structType.Layout.Value.IsDefault ? String.Empty : String.Format("Field={0}", structType.Layout.Value.PackingSize);
if (forceFullType || !(structName.StartsWith("_Anonymous") || innerType))
{
structBuffer.AppendFormat("{0}{1} {2} {3}{4}", indent, strType, structName, packingSpace, nl);
}
else
{
structBuffer.AppendFormat("{0}{1} {2}{3}", indent, strType, packingSpace, nl);
}
HashSet<string> members = memberNames ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (VarType member in structContents)
{
string name = MangleFBKeyword(member.Name);
name = UniquifyName(name, members);
CustomAttributeValues memVals = member.CustomAttributes ?? dummyAttrVals;
SimpleTypeHandleInfo memberType = member.ParamType;
// this has to be special cased as the dimensions attach to the variable name
// rather than the type, but it is by far the least common occurrance
ArrayTypeHandleInfo memberArray = (memberType as ArrayTypeHandleInfo);
SimpleTypeHandleInfo strippedType = PointerTypeHandleInfo.StripAllPointers(memberArray?.DataType ?? memberType).Stripped;
// can't do a nice initialisation if we don't know how long the struct is
if (memVals.flexibleArray)
{
suppressInitWrap = true;
}
if (memVals.bitfields != null)
{
OutputBitfield(structBuffer, memVals.bitfields, memberType, members, memberIndent);
}
else if (!(name.StartsWith("Anonymous") || IsInnerType(strippedType, structType.NestedTypes)))
{
string memAttrStr = FormatMemberAttributeString(memVals, name);
if (memAttrStr.Length > 0)
{
structBuffer.AppendFormat("{0}'' {1}{2}", memberIndent, memAttrStr, nl);
}
SimpleTypeHandleInfo outputType = PtrifyInterfaceType(memberType);
ForwardDeclarationManager.ForwardDeclaration? fwdDeclType = null;
// we need to do this in the non-array case, and in the case the array isn't a string
if ((memberArray == null) || !IsStringArray(memberArray.DataType, name))
{
fwdDeclType = GetForwardDeclarationType(outputType);
if (fwdDeclType.HasValue)
{
outputType = fwdDeclType.Value.Equivalent;
forwardDecls.FormatAndAdd(forwardDeclarations, PointerTypeHandleInfo.StripAllPointers(memberArray?.DataType ?? memberType).Stripped, fwdDeclType.Value.BaseType);
}
}
if (memberArray == null)
{
structBuffer.AppendFormat(
"{0}{1} As {2}{3}{4}",
memberIndent,
name,
memVals.isConst ? "Const " : String.Empty,
outputType,
nl
);
}
else
{
SimpleTypeHandleInfo arrayDataType = memberArray.DataType;
// fixup array of chars to zstring * num instead (0 to x) as char
if (IsStringArray(arrayDataType, name))
{
Debug.Assert(memberArray.Bounds.Rank == 1);
int numElems = memberArray.Bounds.Sizes[0] - memberArray.Bounds.LowerBounds[0];
structBuffer.AppendFormat(
"{0}{1} As {2}{3} * {4}{5}",
memberIndent,
name,
memVals.isConst ? "Const " : String.Empty,
(arrayDataType.TypeInfo == typeof(NonFBChar)) ? "WString" : "ZString",
numElems,
nl
);
}
else
{
structBuffer.AppendFormat(
"{0}{1}{2} As {3}{4}{5}",
memberIndent,
name,
memberArray.DimensionString(),
memVals.isConst ? "Const " : String.Empty,
outputType,
nl
);
}
}
if (!fwdDeclType.HasValue)
{
AddHeaderForType(member.ParamType, headersOut);
}
}
else
{
HandleTypeHandleInfo hInf;
HashSet<string> membersToPass;
bool isPointer = (strippedType != memberType);
bool isArray = (memberArray != null);
bool isIndirect = isPointer | isArray;
if (isArray)
{
hInf = memberArray.DataType as HandleTypeHandleInfo;
membersToPass = null;
}
else
{
hInf = strippedType as HandleTypeHandleInfo;
membersToPass = isPointer ? null : members;
}
StructType<VarType> anonymousType = structType.NestedTypes.Find(
(x) =>
{
return x.Name == hInf.ActualName;
}
);
if (!isIndirect)
{
// Freebasic can only nest anonymous structs and unions if they alternate
bool hasAlternated = (
(strType == "Union") && ((anonymousType.TypeAttributes & TypeAttributes.ExplicitLayout) == 0) ||
(strType == "Type") && ((anonymousType.TypeAttributes & TypeAttributes.ExplicitLayout) != 0)
);
// if we haven't alternated it's FAR easier to synthesize the opposite type and put this inside that
// than it is to rename things, generate the type outside of this nesting level and then generate the definition
if (!hasAlternated)
{
string innerName = "_Anonymous_inner";
TypeAttributes newInnerTypeAttrs = (anonymousType.TypeAttributes ^ TypeAttributes.ExplicitLayout) & TypeAttributes.ExplicitLayout;
if (newInnerTypeAttrs == TypeAttributes.ExplicitLayout)
{
innerName += "_Union";
}
List<StructType<VarType>> inner = new List<StructType<VarType>> { anonymousType };
StructType<VarType> innerTypeWrap = new StructType<VarType>(
innerName,
null,
newInnerTypeAttrs,
null,
inner,
new System.Reflection.Metadata.TypeLayout(0, 0)
);
innerTypeWrap.AddMember(member);
anonymousType = innerTypeWrap;
}
}
bool nonAnonymousOutput = isIndirect;
OutputStruct(structBuffer, forwardDeclarations, headersOut, anonymousType, niceWrappers, memberIndent, membersToPass, nonAnonymousOutput);
if (nonAnonymousOutput)
{
if (isArray)
{
structBuffer.AppendFormat(
"{0}{1}{2} As {3}{4}{5}",
memberIndent,
name,
memberArray.DimensionString(),
memVals.isConst ? "Const " : String.Empty,
memberArray,
nl
);
}
else
{
Debug.Assert(isPointer);
string memberTypeName = memberType.ToString();
int dotPos = memberTypeName.IndexOf('.');
if(dotPos != -1)
{
memberTypeName = memberTypeName.Substring(dotPos + 1);
}
structBuffer.AppendFormat(
"{0}{1} As {2}{3}{4}",
memberIndent,
name,
memVals.isConst ? "Const " : String.Empty,
memberTypeName,
nl
);
}
}
}
}
if (niceWrappers && (!suppressInitWrap) && (attrVals.sizeField.HasValue))
{
ArrayMemorySizeAttribute sizeAttr = attrVals.sizeField.Value;
Debug.Assert(sizeAttr.which == ArrayMemorySizeAttribute.FieldToUse.Struct);
structBuffer.AppendFormat(
"{0}Declare Constructor(){1}" +
"End {3}{1}" +
"{1}" +
"Private Constructor {4}(){1}" +
"{0}{2} = Sizeof(This){1}" +
"End Constructor{1}",
memberIndent,
nl,
MangleFBKeyword(sizeAttr.details.Item2),
strType,
structName
);
}
else
{
structBuffer.AppendFormat("{0}End {1}{2}", indent, strType, innerType ? String.Empty : nl);
}
}
IfDefGuard guardWriter = null;
if (!innerType)
{
if (headersOut.Length > 0)
{
content.AppendLine(headersOut.ToString());
}
guardWriter = new IfDefGuard(content, archIfdef);
if (forwardDeclarations.Length > 0)
{
content.AppendLine(forwardDeclarations.ToString());
}
}
content.AppendLine(structBuffer.ToString());
if (attrVals.ansiApi)
{
string neutralName = structName.Remove(structName.Length - 1);
if (typeRegistry.LookupStruct(ns.Name, neutralName) == null)
{
outputStreams.AnsiDefs.AppendFormat("Type {0} As {1}{2}", neutralName, structName, nl);
}
}
else if (attrVals.unicodeApi)
{
string neutralName = structName.Remove(structName.Length - 1);
if (typeRegistry.LookupStruct(ns.Name, neutralName) == null)
{
outputStreams.UnicodeDefs.AppendFormat("Type {0} As {1}{2}", neutralName, structName, nl);
}
}
if (niceWrappers && !String.IsNullOrEmpty(attrVals.raiiFree))
{
FunctionType freeingFun = typeRegistry.LookupFunction(ns.Name, attrVals.raiiFree);
OutputRAIIWrapper(outputStreams, structName, structName, freeingFun, attrVals);
}
// this is now defined, no need for forward decls now
forwardDecls.ConcreteDeclaration(SignatureTypeProvider.CreateNameOnlyTypeInfo(ns.Name, structName));
guardWriter?.Dispose();
}
private void OutputBitfield(StringBuilder structBuffer, List<BitfieldMember> fields, SimpleTypeHandleInfo underlyingType, HashSet<string> memberNames, string indent)
{
SimpleTypeHandleInfo realType = GetRealType(underlyingType, typeRegistry) ?? underlyingType;
Debug.Assert(realType is PrimitiveTypeHandleInfo, "Bitfield type wasn't primitive?");
// Freebasic doesn't allow bitfields of types bigger than native integer, so if we get any that are bigger than
// int32, split them up into two int32s so the header will compile in both 32 and 64-bit mode
List<BitfieldMember> newBitfields;
if(realType.TypeInfo == typeof(FBTypes.ULongInt) || realType.TypeInfo == typeof(FBTypes.LongInt))
{
newBitfields = new List<BitfieldMember>(fields.Count * 2);
int numFields = fields.Count;
for(int i = 0; i < numFields; ++i)
{
BitfieldMember bm = fields[i];
long newOffset = bm.offset;
if (bm.offset >= 32)
{
newOffset = bm.offset - 32;
}
long overspill = bm.length - (32 - newOffset);
// if this goes over the 4-byte boundary, it needs splitting into two entries
if (overspill > 0)
{
long newLength = (32 - newOffset);
newBitfields.Add(new BitfieldMember(bm.name, newOffset, newLength));
newBitfields.Add(new BitfieldMember(bm.name, 0, overspill));
}
else
{
newBitfields.Add(new BitfieldMember(bm.name, newOffset, bm.length));
}
}
fields = newBitfields;
underlyingType = new PrimitiveTypeHandleInfo(System.Reflection.Metadata.PrimitiveTypeCode.UInt32);
}
long offsetSoFar = 0;
foreach (BitfieldMember bm in fields)
{
Debug.Assert(bm.offset == (offsetSoFar % 32), "There are gaps in this bitfield!");
string bmName = MangleFBKeyword(bm.name);
bmName = UniquifyName(bmName, memberNames);
structBuffer.AppendFormat("{0}{1} : {2} As {3}{4}", indent, bmName, bm.length, MangleFBKeyword(underlyingType.ToString()), nl);
offsetSoFar += bm.length;
}
}
//private void OutputFunctionPtrs(List<FunctionPointerType> funPtrs)
//{
// foreach (FunctionPointerType fnPtr in funPtrs)
// {
// OutputFunctionPtr(fnPtr);
// }
//}
private void OutputFunctionPtr(FunctionPointerType fnPtr)
{
CustomAttributeValues ptrVals = fnPtr.AttributeValues ?? dummyAttrVals;
string archIfDef = GetArchIfdef(ptrVals);
if (archIfDef == null) return;
StringBuilder content = outputStreams.Main;
string ptrName = MangleFBKeyword(fnPtr.Name);
PrintTypeCommentPreamble(content, ptrName, ptrVals);
FunctionType fn = fnPtr.Shape;
ArgListInformation argList = GatherArgList(fn.Arguments, INDENT);
FunctionArgType functionRetType = fn.ReturnType;
SimpleTypeHandleInfo retType = PtrifyInterfaceType(functionRetType.ParamType);
ForwardDeclarationManager.ForwardDeclaration? fwdRetType = GetForwardDeclarationType(retType);
if (fwdRetType.HasValue)
{
retType = fwdRetType.Value.Equivalent;
forwardDecls.FormatAndAdd(
argList.forwardDeclares,
PointerTypeHandleInfo.StripAllPointers(functionRetType.ParamType).Stripped,
fwdRetType.Value.BaseType
);
}
else
{
AddHeaderForType(retType, argList.headers);
}
if(argList.headers.Length > 0)
{
content.AppendLine(argList.headers.ToString());
}
using (IfDefGuard guardWriter = new IfDefGuard(content, archIfDef))
{
if (argList.forwardDeclares.Length > 0)
{
content.AppendLine(argList.forwardDeclares.ToString());
}
bool isFunction = IsFunctionFromReturnType(fn.ReturnType);
content.AppendFormat("Type {0} as {1}(", ptrName, (isFunction ? "Function " : "Sub"));
if(argList.parameters > 1)
{
content.AppendLine(" _");
}
content.Append(argList.argListOutput.ToString());
content.Append(')');
if (isFunction)
{
content.AppendFormat(" As {0}", MangleFBKeyword(retType.ToString()));
}
content.AppendLine(nl);
if (ptrVals.ansiApi)
{
string neutralName = ptrName.Remove(ptrName.Length - 1);
if (typeRegistry.LookupFunctionPtr(ns.Name, neutralName) == null)