This repository has been archived by the owner on Mar 4, 2021. It is now read-only.
/
generator.cs
2437 lines (2079 loc) · 76.1 KB
/
generator.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
//
// This is the binding generator for the MonoTouch API, it uses the
// contract in API.cs to generate the binding.
//
// Authors:
// Geoff Norton
// Miguel de Icaza
//
// Copyright 2009-2010, Novell, Inc.
//
//
// This generator produces various */*.g.cs files based on the
// interface-based type description on this file, see the
// embedded `MonoTouch.UIKit' namespace here for an example
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// TODO:
// * Add support for wrapping "ref" and "out" NSObjects (WrappedTypes)
// Typically this is necessary for things like NSError.
//
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Runtime.InteropServices;
#if MONOMAC
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.CoreGraphics;
using MonoMac.CoreVideo;
#else
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
using MonoTouch.CoreFoundation;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreMedia;
#endif
public static class ReflectionExtensions {
static Type GetBaseType (Type type) {
object [] btype = type.GetCustomAttributes (typeof (BaseTypeAttribute), true);
BaseTypeAttribute bta = btype.Length > 0 ? ((BaseTypeAttribute) btype [0]) : null;
Type base_type = bta != null ? bta.BaseType : typeof (object);
return base_type;
}
public static List <PropertyInfo> GatherProperties (this Type type) {
List <PropertyInfo> properties = new List <PropertyInfo> (type.GetProperties ());
Type parent_type = GetBaseType (type);
string owrap;
string nwrap;
if (parent_type != typeof (NSObject)) {
if (Attribute.IsDefined (parent_type, typeof (ModelAttribute), false)) {
foreach (PropertyInfo pinfo in parent_type.GetProperties ()) {
bool toadd = true;
var modelea = Generator.GetExportAttribute (pinfo, out nwrap);
foreach (PropertyInfo exists in properties) {
var origea = Generator.GetExportAttribute (exists, out owrap);
if (origea.Selector == modelea.Selector)
toadd = false;
}
if (toadd)
properties.Add (pinfo);
}
}
parent_type = GetBaseType (parent_type);
}
return properties;
}
public static List <PropertyInfo> GatherProperties (this Type type, BindingFlags flags) {
List <PropertyInfo> properties = new List <PropertyInfo> (type.GetProperties (flags));
Type parent_type = GetBaseType (type);
string owrap;
string nwrap;
if (parent_type != typeof (NSObject)) {
if (Attribute.IsDefined (parent_type, typeof (ModelAttribute), false)) {
foreach (PropertyInfo pinfo in parent_type.GetProperties (flags)) {
bool toadd = true;
var modelea = Generator.GetExportAttribute (pinfo, out nwrap);
foreach (PropertyInfo exists in properties) {
var origea = Generator.GetExportAttribute (exists, out owrap);
if (origea.Selector == modelea.Selector)
toadd = false;
}
if (toadd)
properties.Add (pinfo);
}
}
parent_type = GetBaseType (parent_type);
}
return properties;
}
public static List <MethodInfo> GatherMethods (this Type type) {
List <MethodInfo> methods = new List <MethodInfo> (type.GetMethods ());
Type parent_type = GetBaseType (type);
if (parent_type != typeof (NSObject)) {
if (Attribute.IsDefined (parent_type, typeof (ModelAttribute), false)) {
methods.AddRange (parent_type.GetMethods ());
}
parent_type = GetBaseType (parent_type);
}
return methods;
}
public static List <MethodInfo> GatherMethods (this Type type, BindingFlags flags) {
List <MethodInfo> methods = new List <MethodInfo> (type.GetMethods (flags));
Type parent_type = GetBaseType (type);
if (parent_type != typeof (NSObject)) {
if (Attribute.IsDefined (parent_type, typeof (ModelAttribute), false)) {
methods.AddRange (parent_type.GetMethods (flags));
}
parent_type = GetBaseType (parent_type);
}
return methods;
}
}
public class RetainListAttribute : Attribute {
public RetainListAttribute (bool doadd, string name)
{
Add = doadd;
WrapName = name;
}
public string WrapName { get; set; }
public bool Add { get; set; }
}
public class RetainAttribute : Attribute {
public RetainAttribute ()
{
}
public RetainAttribute (string wrap)
{
WrapName = wrap;
}
public string WrapName { get; set; }
}
public class PostGetAttribute : Attribute {
public PostGetAttribute (string name)
{
MethodName = name;
}
public string MethodName { get; set; }
}
public class FieldAttribute : Attribute {
public FieldAttribute (string symbolName) {
SymbolName = symbolName;
}
public FieldAttribute (string symbolName, string libraryName) {
SymbolName = symbolName;
LibraryName = libraryName;
}
public string SymbolName { get; set; }
public string LibraryName { get; set; }
}
public class BaseTypeAttribute : Attribute {
public BaseTypeAttribute (Type t)
{
BaseType = t;
}
public Type BaseType { get; set; }
public string Name { get; set; }
public Type [] Events { get; set; }
public string [] Delegates { get; set; }
public bool Singleton { get; set; }
// If set, the code will keep a reference in the EnsureXXX method for
// delegates and will clear the reference to the object in the method
// referenced by KeepUntilRef. Currently uses an ArrayList, so this
// is not really designed as a workaround for systems that create
// too many objects, but two cases in particular that users keep
// trampling on: UIAlertView and UIActionSheet
public string KeepRefUntil { get; set; }
}
//
// Used for methods that invoke other targets, not this.Handle
//
public class BindAttribute : Attribute {
public BindAttribute (string sel)
{
Selector = sel;
}
public string Selector { get; set; }
// By default [Bind] makes non-virtual methods
public bool Virtual { get; set; }
}
public class WrapAttribute : Attribute {
public WrapAttribute (string methodname)
{
MethodName = methodname;
}
public string MethodName { get; set; }
}
// When applied instructs the generator to call Release on the returned objects
// this happens when factory methods in Objetive-C return objects with refcount=1
public class FactoryAttribute : Attribute {
public FactoryAttribute () {}
}
// When applied, it instructs the generator to not use NSStrings for marshalling.
public class PlainStringAttribute : Attribute {
public PlainStringAttribute () {}
}
//
// When applied, instructs the generator to use this object as the
// target, instead of the implicit Handle Can only be used in methods
// that are [Bind] instead of [Export]
//
public class TargetAttribute : Attribute {
public TargetAttribute () {}
}
public class StaticAttribute : Attribute {
public StaticAttribute () {}
}
public class NullAllowedAttribute : Attribute {
public NullAllowedAttribute () {}
}
public class InternalAttribute : Attribute {
public InternalAttribute () {}
}
public class PrivateDefaultCtorAttribute : Attribute {
public PrivateDefaultCtorAttribute () {}
}
// Used for mandatory methods that must be implemented in a [Model].
public class AbstractAttribute : Attribute {
public AbstractAttribute () {}
}
// Used for mandatory methods that must be implemented in a [Model].
public class OverrideAttribute : Attribute {
public OverrideAttribute () {}
}
// Makes the result use the `new' attribtue
public class NewAttribute : Attribute {
public NewAttribute () {}
}
// Makes the result sealed
public class SealedAttribute : Attribute {
public SealedAttribute () {}
}
public class EventArgsAttribute : Attribute {
public EventArgsAttribute (string s)
{
ArgName = s;
}
public EventArgsAttribute (string s, bool skip)
{
ArgName = s;
SkipGeneration = skip;
}
public EventArgsAttribute (string s, bool skip, bool fullname)
{
ArgName = s;
SkipGeneration = skip;
FullName = fullname;
}
public string ArgName { get; set; }
public bool SkipGeneration { get; set; }
public bool FullName { get; set; }
}
//
// Used to specify the delegate type that will be created when
// the generator creates the delegate properties on the host
// class that holds events
//
// example:
// interface SomeDelegate {
// [Export ("foo"), DelegateName ("GetBoolean"), DefaultValue (false)]
// bool Confirm (Some source);
//
public class DelegateNameAttribute : Attribute {
public DelegateNameAttribute (string s)
{
Name = s;
}
public string Name { get; set; }
}
public class EventNameAttribute : Attribute {
public EventNameAttribute (string s)
{
EvtName = s;
}
public string EvtName { get; set; }
}
public class DefaultValueAttribute : Attribute {
public DefaultValueAttribute (object o){
Default = o;
}
public object Default { get; set; }
}
public class DefaultValueFromArgumentAttribute : Attribute {
public DefaultValueFromArgumentAttribute (string s){
Argument = s;
}
public string Argument { get; set; }
}
//
// Used to encapsulate flags about types in either the parameter or the return value
// For now, it only supports the [PlainString] attribute on strings.
//
public class MarshalInfo {
public bool PlainString;
public Type Type;
// Used for parameters
public MarshalInfo (ParameterInfo pi)
{
PlainString = pi.GetCustomAttributes (typeof (PlainStringAttribute), true).Length > 0;
Type = pi.ParameterType;
}
// Used to return values
public MarshalInfo (MethodInfo mi)
{
PlainString = mi.ReturnTypeCustomAttributes.GetCustomAttributes (typeof (PlainStringAttribute), true).Length > 0;
Type = mi.ReturnType;
}
public static bool UseString (ParameterInfo pi)
{
return new MarshalInfo (pi).PlainString;
}
public static implicit operator MarshalInfo (ParameterInfo pi)
{
return new MarshalInfo (pi);
}
public static implicit operator MarshalInfo (MethodInfo mi)
{
return new MarshalInfo (mi);
}
}
public class Tuple<A,B> {
public Tuple (A a, B b)
{
Item1 = a;
Item2 = b;
}
public A Item1;
public B Item2;
}
//
// Encapsulates the information necessary to create a block delegate
//
// The Name is the internal generated name we use for the delegate
// The Parameters is used for the internal delegate signature
// The Invoke contains the invocation steps necessary to invoke the method
//
public class TrampolineInfo {
public string UserDelegate, DelegateName, TrampolineName, Parameters, Invoke;
public TrampolineInfo (string userDelegate, string delegateName, string trampolineName, string pars, string invoke)
{
UserDelegate = userDelegate;
DelegateName = delegateName;
Parameters = pars;
TrampolineName = trampolineName;
Invoke = invoke;
}
public string StaticName {
get {
return "static_" + DelegateName;
}
}
}
public class Generator {
Dictionary<Type,IEnumerable<string>> selectors = new Dictionary<Type,IEnumerable<string>> ();
Dictionary<Type,bool> need_static = new Dictionary<Type,bool> ();
Dictionary<Type,bool> need_abstract = new Dictionary<Type,bool> ();
Dictionary<string,int> selector_use = new Dictionary<string, int> ();
Dictionary<string,string> selector_names = new Dictionary<string,string> ();
Dictionary<string,string> send_methods = new Dictionary<string,string> ();
Dictionary<string,string> original_methods = new Dictionary<string,string> ();
List<MarshalType> marshal_types = new List<MarshalType> ();
Dictionary<Type,TrampolineInfo> trampolines = new Dictionary<Type,TrampolineInfo> ();
Dictionary<Type,Type> delegates_emitted = new Dictionary<Type, Type> ();
public bool Alpha;
public bool OnlyX86;
Type [] types;
bool debug;
bool external;
bool btouch;
StreamWriter sw, m;
int indent;
public class MarshalType {
public Type Type;
public string Encoding;
public string ParameterMarshal;
public string CreateFromRet;
public MarshalType (Type t, string encode, string fetch, string create)
{
Type = t;
Encoding = encode;
ParameterMarshal = fetch;
CreateFromRet = create;
}
}
public bool LookupMarshal (Type t, out MarshalType res)
{
res = null;
foreach (var mt in marshal_types){
if (mt.Type == t){
res = mt;
return true;
}
}
return false;
}
//
// Properties and definitions to support binding third-party Objective-C libraries
//
string init_binding_type;
// Where the assembly messaging is located (core)
public string CoreMessagingNS = "MonoTouch.ObjCRuntime";
// This can be plugged by the user when using btouch/bmac for their own bindings
public string MessagingNS = "MonoTouch.ObjCRuntime";
public bool BindThirdPartyLibrary = false;
public string BaseDir { get { return basedir; } set { basedir = value; }}
string basedir;
public List<string> GeneratedFiles = new List<string> ();
public Type CoreNSObject = typeof (NSObject);
#if MONOMAC
public Type MessagingType = typeof (MonoMac.ObjCRuntime.Messaging);
public Type SampleBufferType = typeof (MonoMac.CoreMedia.CMSampleBuffer);
string [] standard_namespaces = new string [] { "MonoMac.Foundation", "MonoMac.ObjCRuntime", "MonoMac.CoreGraphics" };
const string MainPrefix = "MonoMac";
#else
public Type MessagingType = typeof (MonoTouch.ObjCRuntime.Messaging);
public Type SampleBufferType = typeof (MonoTouch.CoreMedia.CMSampleBuffer);
string [] standard_namespaces = new string [] { "MonoTouch.Foundation", "MonoTouch.ObjCRuntime", "MonoTouch.CoreGraphics" };
const string MainPrefix = "MonoTouch";
#endif
//
// Used by the public binding generator to populate the
// class with types that do not exist
//
public void RegisterMethodName (string method_name)
{
send_methods [method_name] = method_name;
original_methods [method_name] = method_name;
}
//
// Helpers
//
string MakeSig (MethodInfo mi, bool stret) { return MakeSig ("objc_msgSend", stret, mi); }
string MakeSuperSig (MethodInfo mi, bool stret) { return MakeSig ("objc_msgSendSuper", stret, mi); }
bool IsNativeType (Type pt)
{
return (pt == typeof (int) || pt == typeof (long) || pt == typeof (byte) || pt == typeof (short));
}
public string PrimitiveType (Type t)
{
if (t == typeof (void))
return "void";
if (t.IsEnum)
t = Enum.GetUnderlyingType (t);
if (t == typeof (int))
return "int";
if (t == typeof (short))
return "short";
if (t == typeof (byte))
return "byte";
if (t == typeof (float))
return "float";
return t.Name;
}
// Is this a wrapped type of NSObject from the MonoTouch/MonoMac binding world?
public bool IsWrappedType (Type t)
{
if (t.IsInterface)
return true;
if (CoreNSObject != null)
return t.IsSubclassOf (CoreNSObject) || t == CoreNSObject;
return false;
}
//
// Returns the type that we use to marshal the given type as a string
// for example "UIView" -> "IntPtr"
string ParameterGetMarshalType (MarshalInfo mai)
{
if (mai.Type.IsEnum)
return PrimitiveType (mai.Type);
if (IsWrappedType (mai.Type))
return "IntPtr";
if (IsNativeType (mai.Type))
return PrimitiveType (mai.Type);
if (mai.Type == typeof (string)){
if (mai.PlainString)
return "string";
// We will do NSString
return "IntPtr";
}
MarshalType mt;
if (LookupMarshal (mai.Type, out mt))
return mt.Encoding;
if (mai.Type.IsValueType)
return PrimitiveType (mai.Type);
// Arrays are returned as NSArrays
if (mai.Type.IsArray)
return "IntPtr";
//
// Pass "out ValueType" directly
//
if (mai.Type.IsByRef && mai.Type.GetElementType ().IsValueType)
return "out " + mai.Type.GetElementType ().Name;
if (mai.Type.IsSubclassOf (typeof (Delegate))){
return "IntPtr";
}
//
// Edit the table in the "void Go ()" routine
//
if (mai.Type.IsByRef && mai.Type.GetElementType ().IsValueType == false)
return "IntPtr";
Console.WriteLine ("Do not know how to make a signature for {0}", mai.Type);
throw new Exception ();
//return null;
}
//
// This probably should use MarshalInfo to find the correct way of turning
// the native types into managed types instead of hardcoding the limited
// values we know about here
//
public string MakeTrampoline (Type t)
{
if (trampolines.ContainsKey (t))
return trampolines [t].StaticName;
var mi = t.GetMethod ("Invoke");
var pars = new StringBuilder ();
var invoke = new StringBuilder ();
pars.Append ("IntPtr block");
var parameters = mi.GetParameters ();
foreach (var pi in parameters){
pars.Append (", ");
if (pi != parameters [0])
invoke.Append (", ");
if (IsWrappedType (pi.ParameterType)){
pars.AppendFormat ("IntPtr {0}", pi.Name);
invoke.AppendFormat ("({1}) Runtime.GetNSObject ({0})", pi.Name, pi.ParameterType);
continue;
}
if (pi.ParameterType.IsByRef){
var nt = pi.ParameterType.GetElementType ();
if (nt.IsValueType){
pars.AppendFormat ("{0} {1} {2}", pi.IsOut ? "out" : "ref", FormatType (null, nt), pi.Name);
invoke.AppendFormat ("{0} {1}", pi.IsOut ? "out" : "ref", pi.Name);
continue;
}
} else if (pi.ParameterType.IsValueType){
pars.AppendFormat ("{0} {1}", pi.ParameterType.Name, pi.Name);
invoke.AppendFormat ("{0}", pi.Name);
continue;
}
if (pi.ParameterType == typeof (string [])){
pars.AppendFormat ("IntPtr {0}", pi.Name);
invoke.AppendFormat ("NSArray.StringArrayFromHandle ({0})", pi.Name);
continue;
}
if (pi.ParameterType == typeof (string)){
pars.AppendFormat ("IntPtr {0}", pi.Name);
invoke.AppendFormat ("NSString.FromHandle ({0})", pi.Name);
continue;
}
if (pi.ParameterType == SampleBufferType){
pars.AppendFormat ("IntPtr {0}", pi.Name);
invoke.AppendFormat ("new CMSampleBuffer ({0})", pi.Name);
continue;
}
if (pi.ParameterType == typeof (string [])){
pars.AppendFormat ("string [] {0}", pi.Name);
invoke.AppendFormat ("{0}", pi.Name);
continue;
}
if (pi.ParameterType.IsArray){
Type et = pi.ParameterType.GetElementType ();
if (IsWrappedType (et)){
pars.AppendFormat ("IntPtr {0}", pi.Name);
invoke.AppendFormat ("NSArray.ArrayFromHandle<{0}> ({1})", FormatType (null, et), pi.Name);
continue;
}
}
Console.Error.WriteLine ("MakeTrampoline: do not know how to make a trampoline for {0}", pi);
throw new Exception ();
}
var ti = new TrampolineInfo (t.FullName,
"Inner" + t.Name,
"Trampoline" + t.Name,
pars.ToString (), invoke.ToString ());
trampolines [t] = ti;
return ti.StaticName;
}
//
// Returns the actual way in which the type t must be marshalled
// for example "UIView foo" is generated as "foo.Handle"
//
public string MarshalParameter (ParameterInfo pi, bool null_allowed_override)
{
if (pi.ParameterType.IsByRef && pi.ParameterType.GetElementType ().IsValueType == false){
return pi.Name + "Ptr";
}
if (IsWrappedType (pi.ParameterType)){
if (null_allowed_override || HasAttribute (pi, typeof (NullAllowedAttribute)))
return String.Format ("{0} == null ? IntPtr.Zero : {0}.Handle", pi.Name);
return pi.Name + ".Handle";
}
if (pi.ParameterType.IsEnum){
return "(" + PrimitiveType (pi.ParameterType) + ")" + pi.Name;
}
if (IsNativeType (pi.ParameterType))
return pi.Name;
if (pi.ParameterType == typeof (string)){
if (MarshalInfo.UseString (pi))
return pi.Name;
else {
if (null_allowed_override || HasAttribute (pi, typeof (NullAllowedAttribute)))
return String.Format ("ns{0} == null ? IntPtr.Zero : ns{0}.Handle", pi.Name);
else
return "ns" + pi.Name + ".Handle";
}
}
if (pi.ParameterType.IsValueType)
return pi.Name;
MarshalType mt;
if (LookupMarshal (pi.ParameterType, out mt)){
string access = String.Format (mt.ParameterMarshal, pi.Name);
if (null_allowed_override || HasAttribute (pi, typeof (NullAllowedAttribute)))
return String.Format ("{0} == null ? IntPtr.Zero : {1}", pi.Name, access);
return access;
}
if (pi.ParameterType.IsArray){
//Type etype = pi.ParameterType.GetElementType ();
if (null_allowed_override || HasAttribute (pi, typeof (NullAllowedAttribute)))
return String.Format ("nsa_{0} == null ? IntPtr.Zero : nsa_{0}.Handle", pi.Name);
return "nsa_" + pi.Name + ".Handle";
}
//
// Handle (out ValeuType foo)
//
if (pi.ParameterType.IsByRef && pi.ParameterType.GetElementType ().IsValueType){
return "out " + pi.Name;
}
if (pi.ParameterType.IsSubclassOf (typeof (Delegate))){
return String.Format ("(IntPtr) block_ptr_{0}", pi.Name);
}
Console.WriteLine ("Unknown kind {0}", pi);
throw new Exception ();
}
public bool ParameterNeedsNullCheck (ParameterInfo pi, MethodInfo mi)
{
if (HasAttribute (pi, typeof (NullAllowedAttribute)))
return false;
if (mi.IsSpecialName && mi.Name.StartsWith ("set_")){
if (HasAttribute (mi, typeof (NullAllowedAttribute))){
return false;
}
}
if (IsWrappedType (pi.ParameterType))
return true;
if (pi.ParameterType.IsArray)
return true;
if (pi.ParameterType == typeof (Selector))
return true;
if (pi.ParameterType == typeof (Class))
return true;
if (pi.ParameterType == typeof (NSObject))
return true;
if (IsNativeType (pi.ParameterType))
return false;
if (pi.ParameterType == typeof (string))
return true;
if (pi.ParameterType.IsSubclassOf (typeof (Delegate)))
return true;
return false;
}
public object GetAttribute (MethodInfo mi, Type t)
{
object [] a = mi.GetCustomAttributes (t, true);
if (a.Length > 0)
return a [0];
return null;
}
public BindAttribute GetBindAttribute (MethodInfo mi)
{
return GetAttribute (mi, typeof (BindAttribute)) as BindAttribute;
}
public bool HasAttribute (PropertyInfo pi, Type t)
{
return pi.GetCustomAttributes (t, true).Length > 0;
}
public bool HasAttribute (Type queryType, Type t)
{
return queryType.GetCustomAttributes (t, true).Length > 0;
}
public bool HasAttribute (MethodInfo mi, Type t)
{
return mi.GetCustomAttributes (t, true).Length > 0;
}
public bool HasAttribute (ParameterInfo pi, Type t)
{
return pi.GetCustomAttributes (t, true).Length > 0;
}
public bool IsTarget (ParameterInfo pi)
{
return HasAttribute (pi, typeof (TargetAttribute));
}
//
// Makes the method name for a objcSend call
//
string MakeSig (string send, bool stret, MethodInfo mi)
{
var sb = new StringBuilder ();
try {
sb.Append (ParameterGetMarshalType (mi));
} catch {
Console.WriteLine (" in Method `{0}'", mi.Name);
}
sb.Append ("_");
sb.Append (send);
if (stret)
sb.Append ("_stret");
foreach (var pi in mi.GetParameters ()){
if (IsTarget (pi))
continue;
sb.Append ("_");
try {
sb.Append (ParameterGetMarshalType (new MarshalInfo (pi)).Replace (' ', '_'));
} catch {
Console.WriteLine (" in parameter `{0}' from {1}.{2}", pi.Name, mi.DeclaringType, mi.Name);
throw;
}
}
return sb.ToString ();
}
void RegisterMethod (bool need_stret, MethodInfo mi, string method_name)
{
if (send_methods.ContainsKey (method_name))
return;
send_methods [method_name] = method_name;
var b = new StringBuilder ();
int n = 0;
foreach (var pi in mi.GetParameters ()){
if (IsTarget (pi))
continue;
b.Append (", ");
try {
b.Append (ParameterGetMarshalType (pi));
} catch {
Console.WriteLine (" in parameter {0} of {1}.{2}", pi.Name, mi.DeclaringType, mi.Name);
}
b.Append (" ");
b.Append ("arg" + (++n));
}
string entry_point;
if (method_name.IndexOf ("objc_msgSendSuper") != -1){
entry_point = need_stret ? "objc_msgSendSuper_stret" : "objc_msgSendSuper";
} else
entry_point = need_stret ? "objc_msgSend_stret" : "objc_msgSend";
//
// These exist in Messaging.cs and we can not remove them from there
//
switch (method_name){
case "void_objc_msgSend":
case "void_objc_msgSendSuper":
return;
}
print (m, "\t\t[DllImport (LIBOBJC_DYLIB, EntryPoint=\"{0}\")]", entry_point);
print (m, "\t\tpublic extern static {0} {1} ({3}IntPtr receiver, IntPtr selector{2});",
need_stret ? "void" : ParameterGetMarshalType (mi), method_name, b.ToString (),
need_stret ? "out " + FormatType (MessagingType, mi.ReturnType) + " retval, " : "");
}
bool ArmNeedStret (MethodInfo mi)
{
Type t = mi.ReturnType;
if (!t.IsValueType || t.IsEnum || t.Assembly == typeof (object).Assembly)
return false;
return true;
}
bool X86NeedStret (MethodInfo mi)
{
Type t = mi.ReturnType;
if (!t.IsValueType || t.IsEnum || t.Assembly == typeof (object).Assembly)
return false;
return Marshal.SizeOf (t) > 8;
}
bool NeedStret (MethodInfo mi)
{
return ArmNeedStret (mi) || X86NeedStret (mi);
}
void DeclareInvoker (MethodInfo mi)
{
bool arm_stret = ArmNeedStret (mi);
try {
RegisterMethod (arm_stret, mi, MakeSig (mi, arm_stret));
RegisterMethod (arm_stret, mi, MakeSuperSig (mi, arm_stret));
bool x86_stret = X86NeedStret (mi);
if (x86_stret != arm_stret){
RegisterMethod (x86_stret, mi, MakeSig (mi, x86_stret));
RegisterMethod (x86_stret, mi, MakeSuperSig (mi, x86_stret));
}
} catch {
Console.WriteLine (" in Method: {0}", mi);
}
}
//
// Either we have an [Export] attribute, or we have a [Wrap] one
//
public static ExportAttribute GetExportAttribute (PropertyInfo pi, out string wrap)
{
wrap = null;
#if debug
object [] jattrs = pi.GetCustomAttributes (true);
Console.WriteLine ("On: {0}", pi);
foreach (var x in jattrs){
Console.WriteLine (" -> {0} ", x);
Console.WriteLine (" On: {0} ", x.GetType ().Assembly);
Console.WriteLine (" Ex: {0}", typeof (ExportAttribute).Assembly);
}
#endif
object [] attrs = pi.GetCustomAttributes (typeof (ExportAttribute), true);
if (attrs.Length == 0){
attrs = pi.GetCustomAttributes (typeof (WrapAttribute), true);
if (attrs.Length != 0){
wrap = ((WrapAttribute) attrs [0]).MethodName;
return null;
}
return null;
}
return (ExportAttribute) attrs [0];
}
public ExportAttribute MakeSetAttribute (ExportAttribute source)
{
return new ExportAttribute ("set" + Char.ToUpper (source.Selector [0]) + source.Selector.Substring (1) + ":");
}
public Generator (bool btouch, bool external, bool debug, Type [] types)
{
this.btouch = btouch;
this.external = external;
this.debug = debug;
this.types = types;
basedir = ".";