forked from mono/Embeddinator-4000
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objcgenerator.cs
1328 lines (1184 loc) · 49.3 KB
/
objcgenerator.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.IO;
using System.Linq;
using System.Text;
using IKVM.Reflection;
using Type = IKVM.Reflection.Type;
namespace Embeddinator.ObjC {
public partial class ObjCGenerator : Generator {
SourceWriter headers = new SourceWriter ();
SourceWriter private_headers = new SourceWriter ();
SourceWriter implementation = new SourceWriter ();
public override void Generate ()
{
Logger.Log ($"Begin Generator");
var types = Processor.Types;
headers.WriteLine ("#include \"embeddinator.h\"");
headers.WriteLine ("#import <Foundation/Foundation.h>");
headers.WriteLine ();
headers.WriteLine ();
headers.WriteLine ("#if !__has_feature(objc_arc)");
headers.WriteLine ("#error Embeddinator code must be built with ARC.");
headers.WriteLine ("#endif");
headers.WriteLine ();
headers.WriteLine ("#ifdef __cplusplus");
headers.WriteLine ("extern \"C\" {");
headers.WriteLine ("#endif");
headers.WriteLine ("// forward declarations");
foreach (var t in types.Where ((arg) => arg.IsClass))
headers.WriteLine ($"@class {t.TypeName};");
headers.WriteLine ();
private_headers.WriteLine ("#import <Foundation/Foundation.h>");
private_headers.WriteLine ();
implementation.WriteLine ("#include \"bindings.h\"");
implementation.WriteLine ("#include \"bindings-private.h\"");
implementation.WriteLine ("#include \"glib.h\"");
implementation.WriteLine ("#include \"objc-support.h\"");
implementation.WriteLine ("#include \"mono_embeddinator.h\"");
implementation.WriteLine ("#include \"mono-support.h\"");
implementation.WriteLine ();
implementation.WriteLine ("mono_embeddinator_context_t __mono_context;");
implementation.WriteLine ();
foreach (var a in Processor.Assemblies)
implementation.WriteLine ($"MonoImage* __{a.SafeName}_image;");
implementation.WriteLine ();
foreach (var t in types.Where ((arg) => arg.IsClass))
implementation.WriteLine ($"static MonoClass* {t.ObjCName}_class = nil;");
foreach (var t in types.Where ((arg) => arg.IsProtocol)) {
var pname = t.TypeName;
headers.WriteLine ($"@protocol {pname};");
implementation.WriteLine ($"@class __{pname}Wrapper;");
}
headers.WriteLine ();
headers.WriteLine ("NS_ASSUME_NONNULL_BEGIN");
headers.WriteLine ();
implementation.WriteLine ();
implementation.WriteLine ("static void __initialize_mono ()");
implementation.WriteLine ("{");
implementation.Indent++;
implementation.WriteLine ("if (__mono_context.domain)");
implementation.Indent++;
implementation.WriteLine ("return;");
implementation.Indent--;
implementation.WriteLine ("mono_embeddinator_init (&__mono_context, \"mono_embeddinator_binding\");");
implementation.WriteLine ("mono_embeddinator_install_assembly_load_hook (&mono_embeddinator_find_assembly_in_bundle);");
implementation.Indent--;
implementation.WriteLine ("}");
implementation.WriteLine ();
// The generated registrar code calls this method on every entry point.
implementation.WriteLine ("void xamarin_embeddinator_initialize ()");
implementation.WriteLine ("{");
implementation.WriteLine ("\t__initialize_mono ();");
implementation.WriteLine ("}");
implementation.WriteLine ();
base.Generate ();
headers.WriteLine ("NS_ASSUME_NONNULL_END");
headers.WriteLine ();
headers.WriteLine ("#ifdef __cplusplus");
headers.WriteLine ("} /* extern \"C\" */");
headers.WriteLine ("#endif");
}
protected override void Generate (ProcessedAssembly a)
{
Logger.Log ($"Generating Assembly: {a.Name}");
var originalName = a.Name;
var name = a.SafeName;
implementation.WriteLine ($"static void __lookup_assembly_{name} ()");
implementation.WriteLine ("{");
implementation.Indent++;
implementation.WriteLine ($"if (__{name}_image)");
implementation.Indent++;
implementation.WriteLine ("return;");
implementation.Indent--;
implementation.WriteLine ("__initialize_mono ();");
if (name == "mscorlib") {
// skip extra logic - we know mscorlib is already loaded into memory
implementation.WriteLine ($"__{name}_image = mono_get_corlib ();");
} else {
implementation.WriteLine ($"__{name}_image = mono_embeddinator_load_assembly (&__mono_context, \"{originalName}.dll\");");
}
implementation.WriteLine ($"assert (__{name}_image && \"Could not load the assembly '{originalName}.dll'.\");");
var categories = extensions_methods.Keys;
if (categories.Count > 0) {
implementation.WriteLine ("// we cannot use `+initialize` inside categories as they would replace the original type code");
implementation.WriteLine ("// since there should not be tons of them we're pre-loading them when loading the assembly");
foreach (var definedType in extensions_methods.Keys) {
if (definedType.Assembly != a.Assembly)
continue;
var managed_name = NameGenerator.GetObjCName (definedType);
implementation.WriteLineUnindented ("#if TOKENLOOKUP");
implementation.WriteLine ($"{managed_name}_class = mono_class_get (__{name}_image, 0x{definedType.MetadataToken:X8});");
implementation.WriteLineUnindented ("#else");
implementation.WriteLine ($"{managed_name}_class = mono_class_from_name (__{name}_image, \"{definedType.Namespace}\", \"{definedType.Name}\");");
implementation.WriteLineUnindented ("#endif");
}
}
implementation.Indent--;
implementation.WriteLine ("}");
implementation.WriteLine ();
var assembly = a.Assembly;
var types = Processor.Types;
foreach (var t in types.Where ((arg) => arg.IsEnum && arg.Assembly == a)) {
GenerateEnum (t);
}
foreach (var t in types.Where ((arg) => arg.IsProtocol && arg.Assembly == a)) {
GenerateProtocol (t);
}
foreach (var t in types.Where ((arg) => arg.IsClass && arg.Assembly == a)) {
Generate (t);
}
foreach (var extension in extensions_methods) {
var defining_type = extension.Key;
if (defining_type.Assembly != assembly)
continue;
foreach (var category in extension.Value)
GenerateCategory (defining_type, category.Key, category.Value);
}
}
void GenerateCategory (Type definedType, Type extendedType, List<ProcessedMethod> methods)
{
Logger.Log ($"Generating Catagory: {definedType.Name}");
var etn = NameGenerator.GetTypeName (extendedType).Replace (" *", String.Empty);
var name = $"{etn} ({NameGenerator.GetTypeName (definedType)})";
headers.WriteLine ($"/** Category {name}");
headers.WriteLine ($" * Corresponding .NET Qualified Name: `{definedType.AssemblyQualifiedName}`");
headers.WriteLine (" */");
headers.WriteLine ($"@interface {name}");
headers.WriteLine ();
implementation.WriteLine ($"@implementation {name}");
implementation.WriteLine ();
foreach (var mi in methods) {
ImplementMethod (mi);
}
headers.WriteLine ("@end");
headers.WriteLine ();
implementation.WriteLine ("@end");
implementation.WriteLine ();
}
void GenerateEnum (ProcessedType type)
{
Logger.Log ($"Generating Enum: {type.TypeName}");
Type t = type.Type;
var managed_name = type.ObjCName;
var underlying_type = t.GetEnumUnderlyingType ();
var base_type = NameGenerator.GetTypeName (underlying_type);
// it's nicer to expose flags as unsigned integers - but .NET defaults to `int`
bool flags = t.HasCustomAttribute ("System", "FlagsAttribute");
if (flags) {
switch (Type.GetTypeCode (underlying_type)) {
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
base_type = "unsigned " + base_type;
break;
}
}
var macro = flags ? "NS_OPTIONS" : "NS_ENUM";
headers.WriteLine ($"/** Enumeration {managed_name}");
headers.WriteLine ($" * Corresponding .NET Qualified Name: `{t.AssemblyQualifiedName}`");
headers.WriteLine (" */");
headers.WriteLine ($"typedef {macro}({base_type}, {managed_name}) {{");
headers.Indent++;
foreach (var name in t.GetEnumNames ()) {
var value = t.GetField (name).GetRawConstantValue ();
headers.Write ($"{managed_name}{name} = ");
if (flags)
headers.Write ($"0x{value:x}");
else
headers.Write (value);
headers.WriteLine (',');
}
headers.Indent--;
headers.WriteLine ("};");
headers.WriteLine ();
}
void GenerateProtocol (ProcessedType type)
{
Logger.Log ($"Generating Protocol: {type.TypeName}");
Type t = type.Type;
var pbuilder = new ProtocolHelper (headers, implementation, private_headers) {
AssemblyQualifiedName = t.AssemblyQualifiedName,
AssemblyName = type.Assembly.SafeName,
ProtocolName = type.TypeName,
Namespace = t.Namespace,
ManagedName = t.Name,
MetadataToken = t.MetadataToken,
};
pbuilder.BeginHeaders ();
// no need to iterate constructors or fields as they cannot be part of net interfaces
// do not generate implementations for protocols
implementation.Enabled = false;
if (type.HasProperties) {
headers.WriteLine ();
foreach (var pi in type.Properties)
Generate (pi);
}
if (type.HasMethods) {
headers.WriteLine ();
foreach (var mi in type.Methods)
Generate (mi);
}
pbuilder.EndHeaders ();
// wrappers are internal so not part of the headers
headers.Enabled = false;
implementation.Enabled = true;
pbuilder.BeginImplementation ();
if (type.HasProperties) {
implementation.WriteLine ();
foreach (var pi in type.Properties)
Generate (pi);
}
if (type.HasMethods) {
implementation.WriteLine ();
foreach (var mi in type.Methods)
Generate (mi);
}
pbuilder.EndImplementation ();
headers.Enabled = true;
}
protected override void Generate (ProcessedType type)
{
Logger.Log ($"Generating Type: {type.TypeName}");
Type t = type.Type;
var aname = t.Assembly.GetName ().Name.Sanitize ();
var static_type = t.IsSealed && t.IsAbstract;
var managed_name = NameGenerator.GetObjCName (t);
List<string> conformed_protocols = new List<string> ();
foreach (var i in t.GetInterfaces ()) {
if (Processor.Types.HasProtocol (i))
conformed_protocols.Add (NameGenerator.GetObjCName (i));
}
var tbuilder = new ClassHelper (headers, implementation) {
AssemblyQualifiedName = t.AssemblyQualifiedName,
AssemblyName = aname,
BaseTypeName = NameGenerator.GetTypeName (t.BaseType),
Name = NameGenerator.GetTypeName (t),
Namespace = t.Namespace,
ManagedName = (t.DeclaringType != null ? t.DeclaringType.Name + "/" : "") + t.Name,
Protocols = conformed_protocols,
IsBaseTypeBound = Processor.Types.HasClass (t.BaseType),
IsStatic = t.IsSealed && t.IsAbstract,
MetadataToken = t.MetadataToken,
};
tbuilder.BeginHeaders ();
tbuilder.BeginImplementation ();
var default_init = false;
if (type.HasConstructors) {
foreach (var ctor in type.Constructors) {
var pcount = ctor.Parameters.Length;
default_init |= pcount == 0;
var parameters = ctor.Parameters;
string name = ctor.BaseName;
string signature = ".ctor()";
if (parameters.Length > 0) {
name = ctor.ObjCSignature;
signature = ctor.MonoSignature;
}
if (ctor.Unavailable) {
headers.WriteLine ("/** This initializer is not available as it was not re-exposed from the base type");
headers.WriteLine (" * For more details consult https://github.com/mono/Embeddinator-4000/blob/main/docs/ObjC.md#constructors-vs-initializers");
headers.WriteLine (" */");
headers.WriteLine ($"- (nullable instancetype){name} NS_UNAVAILABLE;");
headers.WriteLine ();
continue;
}
if (ctor.ConstructorType == ConstructorType.DefaultValueWrapper) {
default_init |= ctor.FirstDefaultParameter == 0;
GenerateDefaultValuesWrapper (ctor);
continue;
}
var builder = new MethodHelper (headers, implementation) {
AssemblySafeName = aname,
ReturnType = "nullable instancetype",
ManagedTypeName = t.FullName,
MetadataToken = ctor.Constructor.MetadataToken,
MonoSignature = signature,
ObjCSignature = name,
ObjCTypeName = managed_name,
IsConstructor = true,
IsValueType = t.IsValueType,
IgnoreException = true,
};
builder.WriteHeaders ();
builder.BeginImplementation ();
builder.WriteMethodLookup ();
// TODO: this logic will need to be update for managed NSObject types (e.g. from XI / XM) not to call [super init]
implementation.WriteLine ("if (!_object) {");
implementation.Indent++;
implementation.WriteLine ($"MonoObject* __instance = mono_object_new (__mono_context.domain, {managed_name}_class);");
string postInvoke = String.Empty;
var args = "nil";
if (pcount > 0) {
Generate (parameters, false, out postInvoke);
args = "__args";
}
builder.WriteInvoke (args);
implementation.Write (postInvoke);
implementation.WriteLine ("_object = (MonoEmbedObject *)mono_embeddinator_create_object (__instance);");
implementation.Indent--;
implementation.WriteLine ("}");
if (Processor.Types.HasClass (t.BaseType))
implementation.WriteLine ("return self = [super initForSuper];");
else
implementation.WriteLine ("return self = [super init];");
builder.EndImplementation ();
headers.WriteLine ();
}
}
// generate an `init` for a value type (even if none was defined, the default one is usable)
if (!default_init && t.IsValueType) {
var builder = new MethodHelper (headers, implementation) {
AssemblySafeName = aname,
ReturnType = "nullable instancetype",
ManagedTypeName = t.FullName,
MonoSignature = ".ctor()",
ObjCSignature = "init",
ObjCTypeName = managed_name,
IsConstructor = true,
IsValueType = t.IsValueType,
IgnoreException = true,
};
builder.WriteHeaders ();
builder.BeginImplementation ();
// no call to `WriteMethodLookup` since there is not such method if we reached this case
implementation.WriteLine ("if (!_object) {");
implementation.Indent++;
implementation.WriteLine ($"MonoObject* __instance = mono_object_new (__mono_context.domain, {managed_name}_class);");
// no call to `WriteInvoke` since there is not such method if we reached this case
implementation.WriteLine ("_object = (MonoEmbedObject *)mono_embeddinator_create_object (__instance);");
implementation.Indent--;
implementation.WriteLine ("}");
if (HasClass (t.BaseType))
implementation.WriteLine ("return self = [super initForSuper];");
else
implementation.WriteLine ("return self = [super init];");
builder.EndImplementation ();
headers.WriteLine ();
default_init = true;
}
if (!default_init || static_type)
tbuilder.DefineNoDefaultInit ();
if (type.HasProperties) {
headers.WriteLine ();
foreach (var pi in type.Properties)
Generate (pi);
}
if (type.HasFields) {
headers.WriteLine ();
foreach (var fi in type.Fields)
Generate (fi);
}
List<ProcessedProperty> s;
if (subscriptProperties.TryGetValue (t, out s)) {
headers.WriteLine ();
foreach (var si in s)
GenerateSubscript (si);
}
if (type.HasMethods) {
headers.WriteLine ();
foreach (var mi in type.Methods)
Generate (mi);
}
MethodInfo m;
if (icomparable.TryGetValue (t, out m)) {
var pt = m.GetParameters () [0].ParameterType;
var builder = new ComparableHelper (headers, implementation) {
ObjCSignature = $"compare:({managed_name} * _Nullable)other",
AssemblySafeName = aname,
MetadataToken = m.MetadataToken,
ObjCTypeName = managed_name,
ManagedTypeName = t.FullName,
MonoSignature = $"CompareTo({NameGenerator.GetMonoName (pt)})"
};
builder.WriteHeaders ();
builder.WriteImplementation ();
}
tbuilder.EndHeaders ();
tbuilder.EndImplementation ();
}
void Generate (ParameterInfo [] parameters, bool isExtension, out string postInvoke)
{
StringBuilder post = new StringBuilder ();
var pcount = parameters.Length;
implementation.WriteLine ($"void* __args [{pcount}];");
for (int i = 0; i < pcount; i++) {
var p = parameters [i];
var name = (isExtension && (i == 0)) ? "self" : NameGenerator.GetExtendedParameterName (p, parameters);
GenerateArgument (name, $"__args[{i}]", p.ParameterType, ref post);
}
postInvoke = post.ToString ();
}
string GenerateArgumentArrayPost (string parameterName, string argumentName, Type t)
{
var postwriter = new SourceWriter {
Indent = 1
};
var typecode = Type.GetTypeCode (t);
var parrlength = $"__p{parameterName}length";
var presobj = $"__p{parameterName}resobj";
var pindex = $"__p{parameterName}residx";
var pbuff = $"__p{parameterName}buf";
var presarrval = $"__p{parameterName}resarrval";
var ptemp = $"__p{parameterName}tmpobj";
var presarr = $"__{parameterName}arr";
postwriter.WriteLine ();
postwriter.WriteLine ($"if ({presarr}) {{");
postwriter.Indent++;
postwriter.WriteLine ($"int {parrlength} = mono_array_length ({presarr});");
if (typecode != TypeCode.Byte) {
postwriter.WriteLine ($"__strong id * {pbuff} = (id __strong *) calloc ({parrlength}, sizeof (id));");
postwriter.WriteLine ($"id {presobj};");
postwriter.WriteLine ($"int {pindex};");
postwriter.WriteLine ();
postwriter.WriteLine ($"for ({pindex} = 0; {pindex} < {parrlength}; {pindex}++) {{");
postwriter.Indent++;
}
switch (typecode) {
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
var ut = t.IsEnum ? t.GetEnumUnderlyingType () : t;
var ctype = NameGenerator.GetTypeName (ut);
string ctypep;
if (typecode == TypeCode.SByte)
ctypep = "Char"; // GetTypeName returns signed char
else
ctypep = ctype.PascalCase (true);
postwriter.WriteLine ($"{ctype} {presarrval} = mono_array_get ({presarr}, {ctype}, {pindex});");
postwriter.WriteLine ($"{presobj} = [NSNumber numberWith{ctypep}:{presarrval}];");
break;
case TypeCode.Decimal:
postwriter.WriteLine ($"MonoDecimal {presarrval} = mono_array_get ({presarr}, MonoDecimal, {pindex});");
postwriter.WriteLine ($"{presobj} = mono_embeddinator_get_nsdecimalnumber (&{presarrval});");
break;
case TypeCode.DateTime:
postwriter.WriteLine ($"E4KDateTime {presarrval} = mono_array_get ({presarr}, E4KDateTime, {pindex});");
postwriter.WriteLine ($"{presobj} = mono_embeddinator_get_nsdate (&{presarrval});");
break;
case TypeCode.Byte:
postwriter.WriteLine ($"NSData* {presobj} = [NSData dataWithBytes:mono_array_addr ({presarr}, unsigned char, 0) length:{parrlength}];");
break;
case TypeCode.String:
postwriter.WriteLine ($"MonoString* {presarrval} = mono_array_get ({presarr}, MonoString *, {pindex});");
postwriter.WriteLine ($"if ({presarrval})");
postwriter.Indent++;
postwriter.WriteLine ($"{presobj} = mono_embeddinator_get_nsstring ({presarrval});");
postwriter.Indent--;
postwriter.WriteLine ("else");
postwriter.Indent++;
postwriter.WriteLine ($"{presobj} = [NSNull null];");
postwriter.Indent--;
break;
case TypeCode.Object:
var tname = NameGenerator.GetTypeName (t);
if (HasProtocol (t))
tname = "__" + tname + "Wrapper";
postwriter.WriteLine ($"MonoObject* {presarrval} = mono_array_get ({presarr}, MonoObject *, {pindex});");
postwriter.WriteLine ($"if ({presarrval}) {{");
postwriter.Indent++;
postwriter.WriteLine ($"{tname}* {ptemp} = [[{tname} alloc] initForSuper];");
postwriter.WriteLine ($"{ptemp}->_object = (MonoEmbedObject *)mono_embeddinator_create_object ({presarrval});");
postwriter.WriteLine ($"{presobj} = {ptemp};");
postwriter.Indent--;
postwriter.WriteLine ("} else");
postwriter.Indent++;
postwriter.WriteLine ($"{presobj} = [NSNull null];");
postwriter.Indent--;
break;
default:
throw new NotImplementedException ($"Converting type {t.Name} to a native type name");
}
if (typecode == TypeCode.Byte)
postwriter.WriteLine ($"*{parameterName} = {presobj};");
else {
postwriter.WriteLine ($"{pbuff}[{pindex}] = {presobj};");
postwriter.Indent--;
postwriter.WriteLine ("}");
postwriter.WriteLine ($"*{parameterName} = [[NSArray alloc] initWithObjects: {pbuff} count: {parrlength}];");
postwriter.WriteLine ($"for ({pindex} = 0; {pindex} < {parrlength}; {pindex}++)");
postwriter.Indent++;
postwriter.WriteLine ($"{pbuff} [{pindex}] = nil;");
postwriter.Indent--;
postwriter.WriteLine ($"free ({pbuff});");
}
postwriter.Indent--;
postwriter.WriteLine ("}");
postwriter.WriteLine ();
return postwriter.ToString ();
}
void GenerateArgumentArray (string parameterName, string argumentName, Type t, bool is_by_ref, ref StringBuilder post)
{
Type type = t.GetElementType ();
var typeCode = Type.GetTypeCode (type);
var pnameIdx = $"__{parameterName}idx";
var pnameArr = $"__{parameterName}arr";
var pnameRet = $"__{parameterName}ret";
var pnameLength = $"__{parameterName}length";
string arrayCreator = GetArrayCreator (parameterName, type, is_by_ref);
if (is_by_ref)
implementation.WriteLine ($"MonoArray* __{parameterName}arr = nil;");
implementation.WriteLine ($"if (!{(is_by_ref ? "*" : string.Empty)}{parameterName})");
implementation.Indent++;
implementation.WriteLine ($"{argumentName} = {(is_by_ref ? $"&__{parameterName}arr" : "nil")};");
implementation.Indent--;
implementation.WriteLine ("else {");
implementation.Indent++;
implementation.WriteLine ($"uintptr_t {pnameLength} = [{(is_by_ref ? "*" : string.Empty)}{parameterName} {(typeCode == TypeCode.Byte ? "length" : "count")}];");
implementation.WriteLine (arrayCreator);
if (typeCode != TypeCode.Byte) {
implementation.WriteLine ($"int {pnameIdx};");
implementation.WriteLine ($"for ({pnameIdx} = 0; {pnameIdx} < __{parameterName}length; {pnameIdx}++) {{");
implementation.Indent++;
}
switch (typeCode) {
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
var typeName = NameGenerator.GetTypeName (type);
string returnValue;
if (typeCode == TypeCode.SByte) {
returnValue = $"charValue"; // GetTypeName returns signed char
} else {
string returnValueTypeName = type.IsEnum ? NameGenerator.GetTypeName (type.GetEnumUnderlyingType ()) : typeName;
returnValue = $"{returnValueTypeName.CamelCase (true)}Value";
}
implementation.WriteLine ($"NSNumber* {pnameRet} = {(is_by_ref ? $"(*{parameterName})" : parameterName)}[{pnameIdx}];");
implementation.WriteLine ($"if (!{pnameRet} || [{pnameRet} isKindOfClass:[NSNull class]])");
implementation.Indent++;
implementation.WriteLine ($"continue;");
implementation.Indent--;
implementation.WriteLine ($"mono_array_set ({pnameArr}, {typeName}, {pnameIdx}, {pnameRet}.{returnValue});");
break;
case TypeCode.Decimal:
var pparname = is_by_ref ? $"(*{parameterName})" : parameterName;
implementation.WriteLine ($"NSDecimalNumber* {pnameRet} = {pparname}[{pnameIdx}];");
implementation.WriteLine ($"if (!{pnameRet} || [{pnameRet} isKindOfClass:[NSNull class]])");
implementation.Indent++;
implementation.WriteLine ($"continue;");
implementation.Indent--;
implementation.WriteLine ($"mono_array_set ({pnameArr}, MonoDecimal, {pnameIdx}, mono_embeddinator_get_system_decimal ({pnameRet}, &__mono_context));");
break;
case TypeCode.DateTime:
var dtparname = is_by_ref ? $"(*{parameterName})" : parameterName;
implementation.WriteLine ($"NSDate* {pnameRet} = {dtparname}[{pnameIdx}];");
implementation.WriteLine ($"if (!{pnameRet} || [{pnameRet} isKindOfClass:[NSNull class]])");
implementation.Indent++;
implementation.WriteLine ($"continue;");
implementation.Indent--;
implementation.WriteLine ($"mono_array_set ({pnameArr}, E4KDateTime, {pnameIdx}, mono_embeddinator_get_system_datetime ({pnameRet}, &__mono_context));");
break;
case TypeCode.String:
implementation.WriteLine ($"NSString* {pnameRet} = {(is_by_ref ? $"(*{parameterName})" : parameterName)}[{pnameIdx}];");
implementation.WriteLine ($"if (!{pnameRet} || [{pnameRet} isKindOfClass:[NSNull class]])");
implementation.Indent++;
implementation.WriteLine ($"mono_array_set ({pnameArr}, MonoString *, {pnameIdx}, NULL);");
implementation.Indent--;
implementation.WriteLine ("else");
implementation.Indent++;
implementation.WriteLine ($"mono_array_set ({pnameArr}, MonoString *, {pnameIdx}, mono_string_new (__mono_context.domain, [{pnameRet} UTF8String]));");
implementation.Indent--;
break;
case TypeCode.Byte:
implementation.WriteLine ($"int esize = mono_array_element_size (mono_object_get_class ((MonoObject *){pnameArr}));");
implementation.WriteLine ($"char* buff = mono_array_addr_with_size ({pnameArr}, esize, 0);");
implementation.WriteLine ($"[{(is_by_ref ? "*" : string.Empty)}{parameterName} getBytes:buff length:{pnameLength}];");
break;
case TypeCode.Object:
var objcName = NameGenerator.GetObjCName (type);
bool hasClass = false, hasProtocol = false;
if (type.IsInterface)
hasProtocol = HasProtocol (type);
else
hasClass = HasClass (type);
if (hasClass)
implementation.WriteLine ($"{objcName}* {pnameRet} = {(is_by_ref ? $"(*{parameterName})" : parameterName)}[{pnameIdx}];");
else if (hasProtocol)
implementation.WriteLine ($"id<{objcName}> {pnameRet} = {(is_by_ref ? $"(*{parameterName})" : parameterName)}[{pnameIdx}];");
else
goto default;
implementation.WriteLine ($"if (!{pnameRet} || [{pnameRet} isKindOfClass:[NSNull class]])");
implementation.Indent++;
implementation.WriteLine ($"mono_array_set ({pnameArr}, MonoObject *, {pnameIdx}, NULL);");
implementation.Indent--;
implementation.WriteLine ("else");
implementation.Indent++;
if (hasClass)
implementation.WriteLine ($"mono_array_set ({pnameArr}, MonoObject *, {pnameIdx}, mono_gchandle_get_target ({pnameRet}->_object->_handle));");
else if (hasProtocol)
implementation.WriteLine ($"mono_array_set ({pnameArr}, MonoObject *, {pnameIdx}, mono_embeddinator_get_object ({pnameRet}, true));");
break;
default:
throw new NotImplementedException ($"Converting type {type.FullName} to mono code");
}
if (typeCode != TypeCode.Byte) {
implementation.Indent--;
implementation.WriteLine ("}");
}
implementation.WriteLine ($"{argumentName} = {(is_by_ref ? "&" : string.Empty)}{pnameArr};");
implementation.Indent--;
implementation.WriteLine ("}");
if (is_by_ref)
post.AppendLine (GenerateArgumentArrayPost (parameterName, argumentName, type));
}
void GenerateArgument (string paramaterName, string argumentName, Type t, ref StringBuilder post)
{
var is_by_ref = t.IsByRef;
if (is_by_ref)
t = t.GetElementType ();
if (t.IsArray) {
GenerateArgumentArray (paramaterName, argumentName, t, is_by_ref, ref post);
return;
}
switch (Type.GetTypeCode (t)) {
case TypeCode.String:
if (is_by_ref) {
implementation.WriteLine ($"MonoString* __string_{paramaterName} = *{paramaterName} ? mono_string_new (__mono_context.domain, [*{paramaterName} UTF8String]) : nil;");
implementation.WriteLine ($"{argumentName} = &__string_{paramaterName};");
post.AppendLine ($"*{paramaterName} = mono_embeddinator_get_nsstring (__string_{paramaterName});");
} else
implementation.WriteLine ($"{argumentName} = {paramaterName} ? mono_string_new (__mono_context.domain, [{paramaterName} UTF8String]) : nil;");
break;
case TypeCode.Decimal:
implementation.WriteLine ($"MonoDecimal __mdec_{paramaterName} = mono_embeddinator_get_system_decimal ({(is_by_ref ? "*" : string.Empty)}{paramaterName}, &__mono_context);");
implementation.WriteLine ($"{argumentName} = &__mdec_{paramaterName};");
if (is_by_ref)
post.AppendLine ($"*{paramaterName} = mono_embeddinator_get_nsdecimalnumber (&__mdec_{paramaterName});");
break;
case TypeCode.DateTime:
implementation.WriteLine ($"E4KDateTime __mdatetime_{paramaterName} = mono_embeddinator_get_system_datetime ({(is_by_ref ? "*" : string.Empty)}{paramaterName}, &__mono_context);");
implementation.WriteLine ($"{argumentName} = &__mdatetime_{paramaterName};");
if (is_by_ref)
post.AppendLine ($"*{paramaterName} = mono_embeddinator_get_nsdate (&__mdatetime_{paramaterName});");
break;
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
if (is_by_ref)
implementation.WriteLine ($"{argumentName} = {paramaterName};");
else
implementation.WriteLine ($"{argumentName} = &{paramaterName};");
break;
default:
if (t.IsValueType)
implementation.WriteLine ($"{argumentName} = mono_object_unbox (mono_gchandle_get_target ({paramaterName}->_object->_handle));");
else
if (HasClass (t))
implementation.WriteLine ($"{argumentName} = {paramaterName} ? mono_gchandle_get_target ({paramaterName}->_object->_handle): nil;");
else if (HasProtocol (t))
implementation.WriteLine ($"{argumentName} = {paramaterName} ? mono_embeddinator_get_object ({paramaterName}, true) : nil;");
else
throw new NotImplementedException ($"Converting type {t.FullName} to mono code");
break;
}
}
protected override void Generate (ProcessedProperty property)
{
Logger.Log ($"Generating Property: {property.Name}");
var getter = property.GetMethod;
var setter = property.SetMethod;
// setter-only properties are handled as methods (and should not reach this code)
if (getter == null && setter != null)
throw new EmbeddinatorException (99, "Internal error `setter only`. Please file a bug report with a test case (https://github.com/mono/Embeddinator-4000/issues");
headers.Write ("@property (nonatomic");
if (getter.Method.IsStatic)
headers.Write (", class");
if (setter == null)
headers.Write (", readonly");
var pt = property.Property.PropertyType;
var property_type = NameGenerator.GetTypeName (pt);
if (pt.IsInterface)
property_type = $"id<{property_type}>";
if (HasClass (pt))
property_type += " *";
var spacing = property_type [property_type.Length - 1] == '*' ? string.Empty : " ";
headers.WriteLine ($") {property_type}{spacing}{property.Name};");
ImplementMethod (property.GetMethod);
if (setter == null)
return;
ImplementMethod (property.SetMethod);
}
protected void Generate (ProcessedFieldInfo field)
{
Logger.Log ($"Generating Field: {field.Name}");
FieldInfo fi = field.Field;
bool read_only = fi.IsInitOnly || fi.IsLiteral;
headers.Write ("@property (nonatomic");
if (fi.IsStatic)
headers.Write (", class");
if (read_only)
headers.Write (", readonly");
var ft = fi.FieldType;
var bound = HasClass (ft);
if (bound && ft.IsValueType)
headers.Write (", nonnull");
var field_type = NameGenerator.GetTypeName (ft);
if (bound)
field_type += " *";
var spacing = field_type [field_type.Length - 1] == '*' ? string.Empty : " ";
headers.WriteLine ($") {field_type}{spacing}{field.Name};");
// it's similar, but different from implementing a method
var type = fi.DeclaringType;
var managed_type_name = NameGenerator.GetObjCName (type);
var return_type = GetReturnType (type, fi.FieldType);
implementation.Write (fi.IsStatic ? '+' : '-');
implementation.WriteLine ($" ({return_type}) {field.GetterName}");
implementation.WriteLine ("{");
implementation.Indent++;
implementation.WriteLine ("static MonoClassField* __field = nil;");
implementation.WriteLine ("if (!__field) {");
implementation.Indent++;
implementation.WriteLineUnindented ("#if TOKENLOOKUP");
implementation.WriteLine ($"__field = mono_class_get_field ({managed_type_name}_class, 0x{fi.MetadataToken:X8});");
implementation.WriteLineUnindented ("#else");
implementation.WriteLine ($"const char __field_name [] = \"{fi.Name}\";");
implementation.WriteLine ($"__field = mono_class_get_field_from_name ({managed_type_name}_class, __field_name);");
implementation.WriteLineUnindented ("#endif");
implementation.Indent--;
implementation.WriteLine ("}");
var instance = "nil";
if (!fi.IsStatic) {
implementation.WriteLine ($"MonoObject* __instance = mono_gchandle_get_target (_object->_handle);");
instance = "__instance";
}
implementation.WriteLine ($"MonoObject* __result = mono_field_get_value_object (__mono_context.domain, __field, {instance});");
if (HasClass (ft)) {
implementation.WriteLine ("if (!__result)");
implementation.Indent++;
implementation.WriteLine ("return nil;");
implementation.Indent--;
}
ReturnValue (fi.FieldType);
implementation.Indent--;
implementation.WriteLine ("}");
implementation.WriteLine ();
if (read_only)
return;
implementation.Write (fi.IsStatic ? '+' : '-');
implementation.WriteLine ($" (void) {field.SetterName}:({field_type})value");
implementation.WriteLine ("{");
implementation.Indent++;
implementation.WriteLine ("static MonoClassField* __field = nil;");
implementation.WriteLine ("if (!__field) {");
implementation.Indent++;
implementation.WriteLineUnindented ("#if TOKENLOOKUP");
implementation.WriteLine ($"__field = mono_class_get_field ({managed_type_name}_class, 0x{fi.MetadataToken:X8});");
implementation.WriteLineUnindented ("#else");
implementation.WriteLine ($"const char __field_name [] = \"{fi.Name}\";");
implementation.WriteLine ($"__field = mono_class_get_field_from_name ({managed_type_name}_class, __field_name);");
implementation.WriteLineUnindented ("#endif");
implementation.Indent--;
implementation.WriteLine ("}");
StringBuilder sb = null;
implementation.WriteLine ($"void* __value;");
GenerateArgument ("value", "__value", fi.FieldType, ref sb);
if (fi.IsStatic) {
implementation.WriteLine ($"MonoVTable *__vtable = mono_class_vtable (__mono_context.domain, {managed_type_name}_class);");
implementation.WriteLine ("mono_field_static_set_value (__vtable, __field, __value);");
} else {
implementation.WriteLine ($"MonoObject* __instance = mono_gchandle_get_target (_object->_handle);");
implementation.WriteLine ("mono_field_set_value (__instance, __field, __value);");
}
implementation.Indent--;
implementation.WriteLine ("}");
implementation.WriteLine ();
}
public string GetReturnType (Type declaringType, Type returnType)
{
if (HasProtocol (returnType))
return "id<" + NameGenerator.GetTypeName (returnType) + ">";
if (declaringType == returnType)
return "instancetype";
var return_type = NameGenerator.GetTypeName (returnType);
if (HasClass (returnType))
return_type += "*";
return return_type;
}
// TODO override with attribute ? e.g. [ObjC.Selector ("foo")]
string ImplementMethod (ProcessedMethod method)
{
Logger.Log ($"Generating Method Impl: {method}");
MethodInfo info = method.Method;
var type = info.DeclaringType;
var managed_type_name = NameGenerator.GetObjCName (type);
string objcsig = method.ObjCSignature;
var builder = new MethodHelper (headers, implementation) {
AssemblySafeName = type.Assembly.GetName ().Name.Sanitize (),
IsStatic = info.IsStatic,
IsExtension = method.IsExtension,
ReturnType = GetReturnType (type, info.ReturnType),
ManagedTypeName = type.FullName,
MetadataToken = info.MetadataToken,
MonoSignature = method.MonoSignature,
ObjCSignature = objcsig,
ObjCTypeName = managed_type_name,
IsValueType = type.IsValueType,
IsVirtual = info.IsVirtual && !info.IsFinal,
};
if (!method.IsPropertyImplementation)
builder.WriteHeaders ();
builder.BeginImplementation ();
builder.WriteMethodLookup ();
var parametersInfo = method.Parameters;
string postInvoke = String.Empty;
var args = "nil";
if (parametersInfo.Length > 0) {
Generate (parametersInfo, method.IsExtension, out postInvoke);
args = "__args";
}
builder.WriteInvoke (args);
// ref and out parameters might need to be converted back
implementation.Write (postInvoke);
ReturnValue (info.ReturnType);
builder.EndImplementation ();
return objcsig;
}
void GenerateDefaultValuesWrapper (ProcessedMemberWithParameters member)
{
Logger.Log ($"Generating Default Value Wrapper: {member.ObjCSelector}");
ProcessedMethod method = member as ProcessedMethod;
ProcessedConstructor ctor = member as ProcessedConstructor;
if (method == null && ctor == null)
throw new NotSupportedException ("GenerateDefaultValuesWrapper did not get ctor or method?");
MethodBase mb = method != null ? (MethodBase)method.Method : ctor.Constructor;
MethodInfo mi = mb as MethodInfo;
var plist = new List<ParameterInfo> ();
StringBuilder arguments = new StringBuilder ();
headers.WriteLine ("/** This is an helper method that inlines the following default values:");
foreach (var p in member.Parameters) {
string pName = NameGenerator.GetExtendedParameterName (p, member.Parameters);
if (arguments.Length == 0) {