-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathBoundClass.cs
398 lines (308 loc) · 14.9 KB
/
BoundClass.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MonoDroid.Generation;
using Xamarin.Android.Binder;
using Xamarin.SourceWriter;
namespace generator.SourceWriters
{
public class BoundClass : ClassWriter
{
readonly CodeGenerationOptions opt;
readonly List<TypeWriter> sibling_types = new List<TypeWriter> ();
public BoundClass (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorContext context, GenerationInfo generationInfo)
{
context.ContextTypes.Push (klass);
context.ContextGeneratedMethods = new List<Method> ();
generationInfo.TypeRegistrations.Add (new KeyValuePair<string, string> (klass.RawJniName, klass.AssemblyQualifiedName));
var is_enum = klass.base_symbol != null && klass.base_symbol.FullName == "Java.Lang.Enum";
if (is_enum)
generationInfo.Enums.Add (klass.RawJniName.Replace ('/', '.') + ":" + klass.Namespace + ":" + klass.JavaSimpleName);
this.opt = opt;
Name = klass.Name;
SetVisibility (klass.Visibility);
IsShadow = klass.NeedsNew;
IsAbstract = klass.IsAbstract;
IsSealed = klass.IsFinal;
IsPartial = true;
UsePriorityOrder = true;
AddImplementedInterfaces (klass);
klass.JavadocInfo?.AddJavadocs (Comments);
Comments.Add ($"// Metadata.xml XPath class reference: path=\"{klass.MetadataXPathReference}\"");
SourceWriterExtensions.AddObsolete (Attributes, klass.DeprecatedComment, opt, forceDeprecate: klass.IsDeprecated, deprecatedSince: klass.DeprecatedSince);
SourceWriterExtensions.AddRestrictToWarning (Attributes, klass.AnnotatedVisibility, true, opt);
SourceWriterExtensions.AddSupportedOSPlatform (Attributes, klass, opt);
Attributes.Add (new RegisterAttr (klass.RawJniName, null, null, true, klass.AdditionalAttributeString ()) {
UseGlobal = true,
UseShortForm = true,
MemberType = opt.CodeGenerationTarget != CodeGenerationTarget.JavaInterop1 ? null : (MemberTypes?) MemberTypes.TypeInfo,
});
if (klass.TypeParameters != null && klass.TypeParameters.Any ())
Attributes.Add (new CustomAttr (klass.TypeParameters.ToGeneratedAttributeString ()));
// Figure out our base class
string obj_type = null;
if (klass.base_symbol != null)
obj_type = klass.base_symbol is GenericSymbol gs &&
gs.IsConcrete ? gs.GetGenericType (null) : opt.GetOutputName (klass.base_symbol.FullName);
if (klass.InheritsObject && obj_type != null)
Inherits = obj_type;
// Handle fields
var seen = new HashSet<string> ();
SourceWriterExtensions.AddFields (this, klass, klass.Fields, seen, opt, context);
var ic = new InterfaceConstsClass (klass, seen, opt, context);
if (ic.ShouldGenerate)
NestedTypes.Add (ic);
// Sibling classes
if (!klass.AssemblyQualifiedName.Contains ('/')) {
foreach (InterfaceExtensionInfo nestedIface in klass.GetNestedInterfaceTypes ())
if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify))
sibling_types.Add (new InterfaceExtensionsClass (nestedIface.Type, nestedIface.DeclaringType, opt));
}
if (klass.IsAbstract)
sibling_types.Add (new ClassInvokerClass (klass, opt));
AddNestedTypes (klass, opt, context, generationInfo);
AddBindingInfrastructure (klass, opt);
AddConstructors (klass, opt, context);
AddProperties (klass, opt);
AddMethods (klass, opt, context);
AddAbstractMembers (klass, opt, context);
AddExplicitGenericInterfaceMembers (klass, opt);
AddCharSequenceEnumerator (klass);
context.ContextGeneratedMethods.Clear ();
context.ContextTypes.Pop ();
}
void AddBindingInfrastructure (ClassGen klass, CodeGenerationOptions opt)
{
// @class.InheritsObject is true unless @class refers to java.lang.Object or java.lang.Throwable. (see ClassGen constructor)
// If @class's base class is defined in the same api.xml file, then it requires the new keyword to overshadow the internal
// members of its baseclass since the two classes will be defined in the same assembly. If the base class is not from the
// same api.xml file, the new keyword is not needed because the internal access modifier already prevents it from being seen.
var baseFromSameAssembly = klass?.BaseGen?.FromXml ?? false;
var requireNew = klass.InheritsObject && baseFromSameAssembly;
Fields.Add (new PeerMembersField (opt, klass.RawJniName, klass.Name, false));
if (opt.CodeGenerationTarget != CodeGenerationTarget.JavaInterop1) {
Properties.Add (new ClassHandleGetter (requireNew));
}
if (klass.BaseGen != null && klass.InheritsObject) {
Properties.Add (new JniPeerMembersGetter ());
if (opt.CodeGenerationTarget != CodeGenerationTarget.JavaInterop1) {
Properties.Add (new ClassThresholdClassGetter ());
Properties.Add (new ThresholdTypeGetter ());
}
}
}
void AddConstructors (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorContext context)
{
// Add required constructor for all JLO inheriting classes
if (klass.FullName != "Java.Lang.Object" && klass.InheritsObject) {
if (!string.IsNullOrWhiteSpace (klass.PeerConstructorPartialMethod)) {
Methods.Add (new ConstructorPartialMethod (klass.PeerConstructorPartialMethod));
}
Constructors.Add (new JavaLangObjectConstructor (klass, opt, klass.PeerConstructorPartialMethod));
}
foreach (var ctor in klass.Ctors) {
// Don't bind final or protected constructors
if (klass.IsFinal && ctor.Visibility == "protected")
continue;
// Bind Java declared constructor
Constructors.Add (new BoundConstructor(klass, ctor, klass.InheritsObject, opt, context));
// If the constructor takes ICharSequence, create an overload constructor that takes a string
if (ctor.Parameters.HasCharSequence && !klass.ContainsCtor (ctor.JniSignature.Replace ("java/lang/CharSequence", "java/lang/String")))
Constructors.Add (new StringOverloadConstructor(klass, ctor, klass.InheritsObject, opt, context));
}
}
void AddCharSequenceEnumerator (ClassGen klass)
{
if (klass.Interfaces.Any (p => p.FullName == "Java.Lang.ICharSequence")) {
Methods.Add (new CharSequenceEnumeratorMethod ());
Methods.Add (new CharSequenceGenericEnumeratorMethod ());
}
}
void AddImplementedInterfaces (ClassGen klass)
{
foreach (var isym in klass.Interfaces) {
if ((!(isym is GenericSymbol gs) ? isym : gs.Gen) is InterfaceGen gen && (gen.IsConstSugar (opt) || gen.RawVisibility != "public"))
continue;
Implements.Add (opt.GetOutputName (isym.FullName));
}
}
void AddExplicitGenericInterfaceMembers (ClassGen klass, CodeGenerationOptions opt)
{
foreach (var gs in klass.Interfaces.Where (sym => sym is GenericSymbol).Cast<GenericSymbol> ().Where (sym => sym.IsConcrete)) {
// FIXME: not sure if excluding default methods is a valid idea...
foreach (var m in gs.Gen.Methods) {
if (m.IsInterfaceDefaultMethod || m.IsStatic)
continue;
if (m.IsGeneric)
Methods.Add (new GenericExplicitInterfaceImplementationMethod (m, gs, opt));
}
foreach (var p in gs.Gen.Properties) {
if (p.Getter?.IsInterfaceDefaultMethod == true || p.Getter?.IsStatic == true)
continue;
if (p.Setter?.IsInterfaceDefaultMethod == true || p.Setter?.IsStatic == true)
continue;
if (p.IsGeneric) {
var mappings = new Dictionary<string, string> ();
for (var i = 0; i < gs.TypeParams.Length; i++)
mappings [gs.Gen.TypeParameters [i].Name] = gs.TypeParams [i].FullName;
//If the property type is Java.Lang.Object, we don't need to generate an explicit implementation
if (p.Getter?.RetVal.GetGenericType (mappings) == "Java.Lang.Object")
return;
if (p.Setter?.Parameters [0].GetGenericType (mappings) == "Java.Lang.Object")
return;
Properties.Add (new GenericExplicitInterfaceImplementationProperty (p, gs, gs.Gen.AssemblyQualifiedName + "Invoker", mappings, opt));
}
}
}
}
void AddAbstractMembers (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorContext context)
{
if (!klass.IsAbstract)
return;
foreach (var gen in klass.GetAllDerivedInterfaces ())
AddInterfaceAbstractMembers(klass, gen, opt, context);
}
// For each interface, generate either an abstract method or an explicit implementation method.
void AddInterfaceAbstractMembers (ClassGen klass, InterfaceGen iface, CodeGenerationOptions opt, CodeGeneratorContext context)
{
foreach (var method in iface.Methods.Where (m => !m.IsInterfaceDefaultMethod && !m.IsStatic)) {
var mapped = false;
var sig = method.GetSignature ();
if (context.ContextGeneratedMethods.Any (_ => _.Name == method.Name && _.JniSignature == method.JniSignature))
continue;
if (klass.SkippedInterfaceMethods.Contains (method.GetSkipInvokerSignature ()))
continue;
for (var cls = klass; cls != null; cls = cls.BaseGen)
if (cls.ContainsMethod (method, false) || cls != klass && klass.ExplicitlyImplementedInterfaceMethods.Contains (sig)) {
mapped = true;
break;
}
if (mapped)
continue;
if (klass.ExplicitlyImplementedInterfaceMethods.Contains (sig))
Methods.Add (new MethodExplicitInterfaceImplementation(iface, method, opt));
else
AddAbstractMethodDeclaration (klass, method, iface);
context.ContextGeneratedMethods.Add (method);
}
foreach (var prop in iface.Properties.Where (p => !p.Getter.IsInterfaceDefaultMethod && !p.Getter.IsStatic)) {
if (klass.ContainsProperty (prop.Name, false))
continue;
AddAbstractPropertyDeclaration (klass, prop, opt);
}
}
void AddMethods (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorContext context)
{
var methodsToDeclare = klass.Methods.AsEnumerable ();
// This does not exclude overrides (unlike virtual methods) because we're not sure
// if calling the base interface default method via JNI expectedly dispatches to
// the derived method.
var defaultMethods = klass.GetAllDerivedInterfaces ()
.SelectMany (i => i.Methods)
.Where (m => m.IsInterfaceDefaultMethod)
.Where (m => !klass.ContainsMethod (m, false, false));
var overrides = defaultMethods.Where (m => m.OverriddenInterfaceMethod != null);
var overridens = defaultMethods.Where (m => overrides.Where (_ => _.Name == m.Name && _.JniSignature == m.JniSignature)
.Any (mm => mm.DeclaringType.GetAllDerivedInterfaces ().Contains (m.DeclaringType)));
methodsToDeclare = opt.SupportDefaultInterfaceMethods ? methodsToDeclare : methodsToDeclare.Concat (defaultMethods.Except (overridens)).Where (m => m.DeclaringType.IsGeneratable);
foreach (var m in methodsToDeclare) {
var virt = m.IsVirtual;
m.IsVirtual = !klass.IsFinal && virt;
if (m.IsAbstract && m.OverriddenInterfaceMethod == null && (opt.SupportDefaultInterfaceMethods || !m.IsInterfaceDefaultMethod))
AddAbstractMethodDeclaration (klass, m, null);
else
AddMethod (klass, m, opt);
context.ContextGeneratedMethods.Add (m);
m.IsVirtual = virt;
}
var methods = klass.Methods.Concat (klass.Properties.Where (p => p.Setter != null).Select (p => p.Setter));
foreach (var type in methods.Where (m => m.IsListenerConnector && m.EventName != string.Empty).Select (m => m.ListenerType).Distinct ()) {
AddInlineComment ($"#region \"Event implementation for {type.FullName}\"");
SourceWriterExtensions.AddInterfaceListenerEventsAndProperties (this, type, klass, opt);
AddInlineComment ("#endregion");
}
}
void AddAbstractMethodDeclaration (GenBase klass, Method method, InterfaceGen iface)
{
Methods.Add (new BoundMethodAbstractDeclaration (iface, method, opt, klass));
if (method.IsReturnCharSequence || method.Parameters.HasCharSequence)
Methods.Add (new BoundMethodStringOverload (method, opt));
if (method.Asyncify)
Methods.Add (new MethodAsyncWrapper (method, opt));
}
void AddMethod (GenBase klass, Method method, CodeGenerationOptions opt)
{
if (!method.IsValid)
return;
Methods.Add (new BoundMethod(klass, method, opt, true));
var name_and_jnisig = method.JavaName + method.JniSignature.Replace ("java/lang/CharSequence", "java/lang/String");
var gen_string_overload = !method.IsOverride && method.Parameters.HasCharSequence && !klass.ContainsMethod (name_and_jnisig);
if (gen_string_overload || method.IsReturnCharSequence)
Methods.Add (new BoundMethodStringOverload (method, opt));
if (method.Asyncify)
Methods.Add (new MethodAsyncWrapper (method, opt));
}
void AddProperties (ClassGen klass, CodeGenerationOptions opt)
{
foreach (var prop in klass.Properties) {
var get_virt = prop.Getter.IsVirtual;
var set_virt = prop.Setter == null ? false : prop.Setter.IsVirtual;
prop.Getter.IsVirtual = !klass.IsFinal && get_virt;
if (prop.Setter != null)
prop.Setter.IsVirtual = !klass.IsFinal && set_virt;
if (prop.Getter.IsAbstract)
AddAbstractPropertyDeclaration (klass, prop, opt);
else
AddProperty (klass, prop, opt);
prop.Getter.IsVirtual = get_virt;
if (prop.Setter != null)
prop.Setter.IsVirtual = set_virt;
}
}
void AddProperty (ClassGen klass, Property property, CodeGenerationOptions opt)
{
var bound_property = new BoundProperty (klass, property, opt, true, false);
Properties.Add (bound_property);
if (property.Type.StartsWith ("Java.Lang.ICharSequence", StringComparison.Ordinal) && !bound_property.IsOverride)
Properties.Add (new BoundPropertyStringVariant (property, opt, bound_property));
}
void AddAbstractPropertyDeclaration (ClassGen klass, Property property, CodeGenerationOptions opt)
{
var baseProp = klass.BaseSymbol?.GetPropertyByName (property.Name, true);
if (baseProp != null) {
if (baseProp.Type != property.Getter.Return) {
// This may not be required if we can change generic parameter support to return constrained type (not just J.L.Object).
AddInlineComment ($"// skipped generating property {property.Name} because its Java method declaration is variant that we cannot represent in C#");
return;
}
}
var bound_property = new BoundAbstractProperty (klass, property, opt);
Properties.Add (bound_property);
if (property.Type.StartsWith ("Java.Lang.ICharSequence", StringComparison.Ordinal))
Properties.Add (new BoundPropertyStringVariant (property, opt, bound_property));
}
void AddNestedTypes (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorContext context, GenerationInfo genInfo)
{
foreach (var nest in klass.NestedTypes) {
if (klass.BaseGen?.ContainsNestedType (nest) == true && nest is ClassGen c)
c.NeedsNew = true;
NestedTypes.Add (SourceWriterExtensions.BuildManagedTypeModel (nest, opt, context, genInfo));
}
}
public override void Write (CodeWriter writer)
{
base.Write (writer);
WriteSiblingClasses (writer);
}
public void WriteSiblingClasses (CodeWriter writer)
{
foreach (var sibling in sibling_types) {
writer.WriteLine ();
sibling.Write (writer);
}
}
}
}