-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathgenswift.java
More file actions
1838 lines (1537 loc) · 80.3 KB
/
genswift.java
File metadata and controls
1838 lines (1537 loc) · 80.3 KB
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
//
// genswift.java
// https://github.com/SwiftJava/SwiftJava
// $Id: //depot/SwiftJava/src/genswift.java#95 $
//
// Created by John Holdsworth on 14/07/2016.
// Copyright (c) 2016 John Holdsworth. All rights reserved.
// MIT License
//
// See ../genswift.sh for details on invocation.
// Code generator for Swift written in the style of a Perl script.
//
// Requires https://github.com/SwiftJava/java_swift release 2.1.0+
//
// List of classes to be generated received on stdin which is the
// output of a grep on the target jar for the classes of interest.
//
// The ordering of frameworks can be specified in argv[0] otherwise
// the ordering is found by processing all files then re-processing
// after reordering to minimise the number of forward references in
// the generated code. argv[1] can be the destination directory for
/// generated Swift and argv[2] can be the root for Java generation.
//
// For Java classes, a Swift class of the same name is generated in
// a framework derived from the first two packages of the classes
// full name (e.g. java_lang, java_util.) For Java interfaces a
// Swift protocol is generated along with a concrete class with
// "Forward" added that can be used to message to instances of
// the protocol from Swift.
//
// Where the interface is java.lang.Runnable or the interface name
// ends in "Listener", "Handler" or "Manager" an additional "Base"
// class is generated, instances of which can be passed to Java and
// have Swift methods in a subclass called from Java. This is used
// in threading and in event processing in Swift. These "Base" classes
// are also generated for concrete classes with names ending in "Adapter".
// These seemingly arbitrary conventions are taken from java.awt & swing.
//
// A variation on this forwarding of Java methods into Swift is where
// a method is generally a subclasses responsibility to implement such
// as the method java.awt.Canvas.paint(). A list of these methods must
// be maintained in this source and where one is encountered a "Base"
// class is generated allowing the method to be implemented in Swift.
//
// For this proxy of Java methods into Swift, support is required on
// the Java side of the divide. Proxy classes delegating to "native"
// implementations of the relevant method are generated and must be
// available to the application. On UNIX this is through the jar file
// ~/.swiftjava.jar built from these generated sources using ../genjar.sh.
//
//
// MIT License
//
// Copyright (c) 2016-7, John Holdsworth
//
// 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.
//
import java.io.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Comparator;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class genswift {
static void print( String s ) {
System.out.println(s);
}
static void progress( Object o ) {
//print( o.toString() );
}
static int apiVersion = 2;
static String Unavailable = "Unavailable";
static String pathToWriteSource = "./";
static String organisation = "org.swiftjava.";
static String proxySourcePath = organisation.replace('.', '/');
static String repoBase = "https://github.com/SwiftJava/";
static boolean sortMembers = true, convertEnums = true, returnImplicitlyUnwrapped = true;
boolean isUnavailable( Class<?> type ) {
return notVoid(type) && swiftTypeFor(type, false, true).indexOf(Unavailable) != -1;
}
static HashMap<String,Boolean> swiftKeywords = new HashMap<String,Boolean>() {
private static final long serialVersionUID = 1L;
{
put( "init", true );
put( "self", true );
put( "new", true );
put( "in", true );
put( "is", true );
put( "operator", true );
put( "subscript", true );
put( "where", true );
put( "as", true );
}
};
static HashMap<String,Boolean> swiftReserved = new HashMap<String,Boolean>() {
private static final long serialVersionUID = 1L;
{
put( Float.class.getName(), true );
put( Double.class.getName(), true );
put( Class.class.getName(), true );
put( Object.class.getName(), true );
put( Enum.class.getName(), true );
put( Thread.class.getName(), true );
put( String.class.getName(), true );
put( Comparable.class.getName(), true );
put( Error.class.getName(), true );
put( SecurityException.class.getName(), true );
put( java.util.Map.class.getName(), true );
put( java.util.Set.class.getName(), true );
put( java.util.Locale.class.getName(), true );
put( java.util.Comparator.class.getName(), true );
put( javax.swing.text.TabSet.class.getName(), true );
}
};
static HashMap<String,Boolean> keyClasses = new HashMap<String,Boolean>() {
private static final long serialVersionUID = 1L;
{
put( Object.class.getName(), true );
put( Class.class.getName(), true );
put( Enum.class.getName(), true );
put( Thread.class.getName(), true );
put( Runnable.class.getName(), true );
put( Throwable.class.getName(), true );
put( Exception.class.getName(), true );
put( java.util.Set.class.getName(), true );
put( java.util.Map.class.getName(), true );
put( java.util.HashMap.class.getName(), true );
}
};
static HashMap<String,Boolean> subclassResponsibilities = new HashMap<String,Boolean>() {
private static final long serialVersionUID = 1L;
{
put( "public void java.awt.Window.paint(java.awt.Graphics)", true );
put( "public void java.awt.Canvas.paint(java.awt.Graphics)", true );
put( "public void java.awt.Canvas.update(java.awt.Graphics)", true );
put( "public java.awt.Component javax.swing.JTable.prepareRenderer(javax.swing.table.TableCellRenderer,int,int)", true );
put( "public void javax.swing.text.PlainDocument.insertString(int,java.lang.String,javax.swing.text.AttributeSet) throws javax.swing.text.BadLocationException", true );
put( "public java.awt.Component javax.swing.table.DefaultTableCellRenderer.getTableCellRendererComponent(javax.swing.JTable,java.lang.Object,boolean,boolean,int,int)", true );
put( "public boolean javax.swing.table.DefaultTableModel.isCellEditable(int,int)", true );
put( "public void javax.swing.JTable.changeSelection(int,int,boolean,boolean)", true );
}
};
static HashMap<String,String> swiftTypes = new HashMap<String,String>() {
private static final long serialVersionUID = 1L;
{
put( "boolean", "Bool");
put( "byte", "Int8");
put( "char", "UInt16");
put( "short", "Int16");
put( "int", "Int");
put( "long", "Int64");
put( "float", "Float");
put( "double", "Double");
put( Float.class.getName(), "Float");
put( String.class.getName(), "String");
}
};
static HashMap<String,String> arrayTypes = new HashMap<String,String>() {
private static final long serialVersionUID = 1L;
{
put( "boolean", "Bool");
put( "byte", "Int8");
put( "char", "UInt16");
put( "short", "Int16");
put( "int", "Int32");
put( "long", "Int64");
put( "float", "Float");
put( "double", "Double");
put( String.class.getName(), "String");
}
};
static HashMap<String,String> funcNames = new HashMap<String,String>() {
private static final long serialVersionUID = 1L;
{
put( "boolean", "Boolean");
put( "byte", "Byte");
put( "char", "Char");
put( "short", "Short");
put( "int", "Int");
put( "long", "Long");
put( "float", "Float");
put( "double", "Double");
put( "void", "Void");
}
};
static HashMap<String,String> jvalueFields = new HashMap<String,String>() {
private static final long serialVersionUID = 1L;
{
put( "boolean", "z");
put( "byte", "b");
put( "char", "c");
put( "short", "s");
put( "int", "i");
put( "long", "j");
put( "float", "f");
put( "double", "d");
put( "void", "v");
}
};
boolean excludeFromCodeGeneration( Class<?> clazz ) {
String className = clazz.getName();
return !Modifier.isPublic(clazz.getModifiers())
|| classPrefix(className).equals("java_util") && className.indexOf('$') != -1
|| className.equals("java.util.concurrent.CompletableFuture");
}
boolean supportsProxyCallback( Class<?> clazz ) {
if ( false )
return clazz.isInterface() && !dontEnforceProtocol( clazz ) && !clazz.getName().startsWith("java.util.") || isAdapter();
String clazzName = clazz.getName();
while ( clazzName.charAt(className.length()-1) == ']' )
clazzName = clazzName.substring(0, clazzName.length()-1 );
return clazz == java.lang.Runnable.class || isAdapter() || clazz.isInterface() &&
(clazzName.endsWith("Listener") || clazzName.endsWith("Handler")
|| clazzName.endsWith("Manager"));// || clazzName.indexOf(".swiftbindings.") != -1);
}
boolean isAdapter() {
return classSuffix.endsWith("Adapter");
}
String frameworkImports;
HashMap<String,Boolean> referencedFrameworks = new HashMap<String,Boolean>();
static int filesWritten = 0;
static int frameworkLevel = 0;
static int UnavailableReferences = 0;
static String invocation = "genswift.java", packageOrder, swiftSourceRoot, javaSourceRoot;
public static void main( String args[] ) {
for ( int i=0 ; i<args.length ; i++ )
invocation += " '"+args[i]+"'";
switch ( args.length ) {
case 3:
javaSourceRoot = args[2];
case 2:
swiftSourceRoot = args[1];
default:
packageOrder = args[0];
}
String knownFrameworkOrder[] = ("java_swift|"+packageOrder).split("\\|");
for ( frameworkLevel=0 ; frameworkLevel<knownFrameworkOrder.length ; frameworkLevel++ ) {
String framework = classPrefix(knownFrameworkOrder[frameworkLevel].replace('/', '.')+".");
frameworkLevels.put( framework, frameworkLevel );
knownAdditionalFrameworks.put(framework, true);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> paths = new ArrayList<String>();
String pathToClass;
while ((pathToClass = reader.readLine())!= null) {
paths.add(pathToClass);
try {
genswift generator = new genswift( pathToClass );
if ( generator.generate() )
generator.save();
}
catch ( Exception e ) {
e.printStackTrace();
System.exit(1);
}
}
if ( additionalFrameworks.size() > 1 ) {
HashMap<String,Integer> alreadyMoved = new HashMap<String, Integer>();
for ( int i=0; i<additionalFrameworks.size(); i++ ) {
String mightMove = additionalFrameworks.get(i);
if ( alreadyMoved.containsKey(mightMove) && alreadyMoved.get(mightMove) > 10 )
continue;
int mustBeAfter = i;
for ( int j=i+1; j<additionalFrameworks.size(); j++ )
if (references(mightMove, additionalFrameworks.get(j)) >
references(additionalFrameworks.get(j), mightMove) )
mustBeAfter = j;
if ( mustBeAfter > i ) {
print("Moving "+mightMove+"["+i+"] after "+additionalFrameworks.get(mustBeAfter)+"["+mustBeAfter+"]");
additionalFrameworks.remove(i);
additionalFrameworks.add(mustBeAfter, mightMove);
if ( !alreadyMoved.containsKey(mightMove) )
alreadyMoved.put(mightMove, 1);
else
alreadyMoved.put(mightMove, alreadyMoved.get(mightMove)+1);
i--;
}
}
frameworkLevel = knownFrameworkOrder.length;
for ( int i=0; i<additionalFrameworks.size(); i++ )
if ( frameworkLevels.containsKey(additionalFrameworks.get(i)) )
frameworkLevels.put( additionalFrameworks.get(i), frameworkLevel++ );
for ( String newFramework : additionalFrameworks ) {
StringBuilder pkg = new StringBuilder();
pkg.append( "\nimport PackageDescription\n\nlet package = Package(\n");
pkg.append(" name: \""+newFramework+"\",\n dependencies: [\n");
if ( crossReferences.containsKey(newFramework) )
for ( String depend : crossReferences.get(newFramework).keySet() )
if ( !newFramework.equals(depend) ) {
if ( forwardReference( newFramework, depend ) )
pkg.append("//");
pkg.append(" .Package(url: \"" + repoBase + depend +
".git\", versions: Version("+apiVersion+",0,0)..<Version("+(apiVersion+1)+",0,0)),\n");
}
pkg.append(" ]\n)\n");
try {
FileOutputStream out = new FileOutputStream( pathToWriteSource+newFramework+"/Package.swift" );
out.write( pkg.toString().getBytes("UTF-8") );
out.close();
}
catch ( IOException e ) {}
}
int beforeReorder = UnavailableReferences;
UnavailableReferences = 0;
for ( int i=0; i<paths.size(); i++ ) {
pathToClass = paths.get(i);
try {
genswift generator = new genswift( pathToClass );
if ( generator.generate() )
generator.save();
}
catch ( Exception e ) {
e.printStackTrace();
}
}
print( "Reorder "+beforeReorder+" -> "+UnavailableReferences );
}
}
catch ( IOException e ) {
e.printStackTrace();
}
print("\n"+filesWritten+" files written.");
}
StringBuilder code = new StringBuilder();
String pathToClass, className, classSuffix, currentFramework, visibility, classCacheVar;
boolean isInterface, isEnum, isLost;
Class<?> clazz, superclazz;
genswift( String pathToClass ) {
this.pathToClass = pathToClass;
}
boolean generate() throws Exception {
className = pathToClass.replace('/', '.');
clazz = Class.forName( className );
print( "\n"+clazz );
if ( excludeFromCodeGeneration( clazz ) )
return false;
classSuffix = classSuffix( className );
currentFramework = classPrefix( className );
if ( !frameworkLevels.containsKey(currentFramework) )
frameworkLevels.put( currentFramework, frameworkLevel++ );
if ( !knownAdditionalFrameworks.containsKey(currentFramework) ) {
knownAdditionalFrameworks.put(currentFramework, true);
additionalFrameworks.add(currentFramework);
}
frameworkImports = keyClasses.containsKey(className) ? "" : "\nimport java_swift\n";
visibility = "open ";
superclazz = clazz.getSuperclass();
isInterface = clazz.isInterface();
isEnum = isEnum( clazz );
code.append("\n/// generated by: "+invocation+" ///\n");
// code.append("\n/// JAVA_HOME: "+System.getenv("JAVA_HOME")+" ///\n");
// code.append("/// "+new java.util.Date()+" ///\n");
code.append("\n/// "+clazz+" ///\n");
isLost = false;
String derivedFrom = "";
if (superclazz != null) {
String sname = classTypeFor(superclazz, false, true);
isLost = sname.indexOf(Unavailable+"Object") != -1;
derivedFrom += ": " + sname;
} else if (!isInterface)
derivedFrom += ": JNIObject";
ArrayList<Class<?>> interfacesSoFar = new ArrayList<Class<?>>();
Class<?> supr = superclazz;
while( supr != null ) {
interfacesSoFar.add(supr);
supr = supr.getSuperclass();
}
boolean hasUnavailable = false;
for (Class<?> intrface : clazz.getInterfaces()) {
if ( interfacesChangingReturnTypeInSubclass( intrface ) )
continue;
if ( redundantConformance( intrface, interfacesSoFar.toArray( new Class<?>[ interfacesSoFar.size() ] ) )
|| excludeFromCodeGeneration(intrface) )
continue;
interfacesSoFar.add( intrface );
String name = classTypeFor(intrface, false, true);
boolean isUnavailable = name.indexOf(Unavailable+"Protocol") != -1;
if ( isUnavailable )
if ( hasUnavailable )
continue;
else
hasUnavailable = true;
if (derivedFrom == "")
derivedFrom += ": ";
else
derivedFrom += ", ";
derivedFrom += classTypeFor(intrface, false, true)+(isInterface?"":"");
}
if (isInterface && derivedFrom == "")
derivedFrom += ": JavaProtocol";
code.append("\n"+(isEnum ? "public enum" : isInterface ? "public protocol" : "open class") + " " +
classSuffix+(isInterface?"" : "") + (isEnum ? ": Int, JNIObjectProtocol, JNIObjectInit" : derivedFrom) + " {\n\n");
if ( isEnum ) {
String cases = "";
for ( Object constant : clazz.getEnumConstants() )
cases += (cases == "" ? "" : ", ") + ((Enum<?>)constant).name();
code.append(" case "+cases+"\n\n");
code.append(" static let enumConstants = JavaClass(loading: \""+clazz.getName()+"\")\n" +
" .getEnumConstants()!.map { "+classSuffix+"Forward( javaObject: $0.javaObject ) }\n\n");
code.append(" public func underlier() -> "+classSuffix+"Forward"+" {\n");
code.append(" return "+classSuffix+".enumConstants[self.rawValue]\n }\n\n");
code.append(" public func localJavaObject(_ locals: UnsafeMutablePointer<[jobject]>) -> jobject? {\n");
code.append(" return underlier().localJavaObject( locals )\n }\n\n");
code.append(" public init( javaObject: jobject? ) {\n");
code.append(" self = "+classSuffix+"( rawValue: JavaEnum( javaObject: javaObject ).ordinal() )!\n }\n\n");
}
else if ( !isInterface ) {
code.append(" public convenience init?( casting object: "+swiftTypeFor( java.lang.Object.class, false, true )+", _ file: StaticString = #file, _ line: Int = #line ) {\n");
code.append(" self.init( javaObject: nil )\n" );
if ( frameworkImports.indexOf("import java_lang") != -1 ) {
code.append(" if !object.validDownCast( toJavaClass: \""+className+"\", file, line ) {\n" );
code.append(" return nil\n");
code.append(" }\n");
}
code.append(" object.withJavaObject {\n");
code.append(" self.javaObject = $0\n");
code.append(" }\n");
code.append(" }\n\n" );
}
classCacheVar = classSuffix+"JNIClass";
if ( !isInterface && !isEnum )
code.append( " private static var "+classCacheVar+": jclass?\n\n" );
HashMap<String,Boolean> fieldsSeen = new HashMap<String,Boolean>();
findInterfaceMethods( clazz );
if ( !isEnum ) {
generateFields( fieldsSeen, isInterface, clazz );
if ( !isInterface )
for ( Class<?> intrface : interfacesSoFar.toArray( new Class<?>[ interfacesSoFar.size() ] ) )
generateInterfaceFields( fieldsSeen, intrface );
generateConstructors( pathToClass, classSuffix, false );
}
generateMethods( clazz.getDeclaredMethods(), isInterface, fieldsSeen, classSuffix, false );
ArrayList<java.lang.reflect.Method> responsibles = new ArrayList<java.lang.reflect.Method>();
for ( java.lang.reflect.Method method : clazz.getMethods() ) {
if ( subclassResponsibilities.containsKey(method.toString()) )
responsibles.add( method );
}
if ( !isInterface && !isEnum )
addAnyMethodsDeclaredInProtocolsButNotDefined( isInterface, fieldsSeen, classSuffix );
code.append("}\n\n");
if ( isInterface || isEnum ) {
String superProtocol = "JNIObjectForward";
if ( clazz.getInterfaces().length != 0 )
superProtocol = classTypeFor( clazz.getInterfaces()[0], false, true )+"Forward";
code.append( "\nopen class "+classSuffix+"Forward: "+superProtocol+(isEnum ? "" : ", "+classSuffix)+" {\n\n" );
code.append( " private static var "+classCacheVar+": jclass?\n\n" );
findInterfaceMethods( clazz );
fieldsSeen = new HashMap<String,Boolean>();
generateFields( fieldsSeen, false, clazz );
boolean subinterface = clazz.getInterfaces().length == 1 && clazz.getDeclaredMethods().length == 0;
if ( !subinterface || isEnum ) {
isEnum = false;
generateMethods( clazz.getMethods(), false, fieldsSeen, classSuffix+"Forward", false );
addAnyMethodsDeclaredInProtocolsButNotDefined( false, fieldsSeen, classSuffix+"Forward" );
}
code.append( "}\n\n" );
}
if ( isInterface && supportsProxyCallback( clazz ) || isAdapter() || !responsibles.isEmpty() )
generateCallbackBase( fieldsSeen, responsibles.toArray( new java.lang.reflect.Method[ responsibles.size() ] ) );
return true;
}
void save() throws IOException {
String Sources = swiftSourceRoot != null ? swiftSourceRoot+"/" :
pathToWriteSource + currentFramework + "/Sources/";
new File( Sources ).mkdirs();
String source = Sources + classSuffix + ".swift";
byte bytes[] = (frameworkImports+code.toString()).getBytes("UTF-8");
if ( bytes.length == new File( source ).length() && java.util.Arrays.equals( bytes, existing( source )) )
return;
print( "Saving: "+source);
FileOutputStream out = new FileOutputStream( source );
out.write( bytes );
out.close();
filesWritten++;
}
byte [] existing( String source ) throws IOException {
File file = new File( source );
if ( !file.exists() )
return null;
byte bytes[] = new byte[ (int) file.length() ];
FileInputStream in = new FileInputStream( source );
in.read( bytes );
in.close();
return bytes;
}
int idcount = 0;
void generateFields( HashMap<String,Boolean> fieldsSeen, boolean isInterface, Class<?> clazz ) {
Field fields[] = clazz.getDeclaredFields();
if ( sortMembers )
java.util.Arrays.sort( fields, new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
int statics = compareStatic( o1.getModifiers(), o2.getModifiers() );
return statics != 0 ? statics : o1.getName().compareTo(o2.getName());
}
} );
for (Field field : fields) {
progress(field);
code.append( " /// "+field+"\n\n" );
int mods = field.getModifiers();
String fieldName = safe(field.getName());
boolean isFinal = Modifier.isFinal(mods);
boolean isStatic = Modifier.isStatic(mods);
if ( skipBecause( "field", field, new boolean [] {
!Modifier.isPublic(mods) && !Modifier.isProtected(mods),
fieldOverride( field, superclazz) && isStatic,
fieldsSeen.containsKey(fieldName),
fieldName.equals(classSuffix),
interfaceMethods.containsKey(fieldName+"()"),
isStatic && (Modifier.isProtected(mods) || isInterface /*|| ////
superclazz == javax.swing.undo.AbstractUndoableEdit.class ||
superclazz != null && superclazz.getSuperclass() == javax.swing.undo.AbstractUndoableEdit.class ||
superclazz == javax.swing.plaf.basic.BasicComboBoxRenderer.class ||
superclazz == javax.swing.border.TitledBorder.class*/)
} ) )
continue;
fieldsSeen.put(fieldName, true);
Class<?> fieldType = field.getType();
try {
if ( superclazz != null )
fieldType = superclazz.getField(field.getName()).getType();
}
catch ( NoSuchFieldException e ) {
}
boolean arrayType = crashesCompilerOnLinx(fieldType);
if ( arrayType )
code.append( " #if !os(Linux)\n");
String fieldIDVar = safe(field.getName())+"_FieldID";
if ( ! isInterface )
code.append( " private static var "+fieldIDVar+": jfieldID?\n\n" );
if ( !isStatic )
fieldIDVar = classSuffix+"."+fieldIDVar;
code.append( " "+(fieldOverride(field,superclazz)&&!isLost?"override ":"")+(isInterface?"":visibility)+
(Modifier.isStatic(mods) ? "static " : "")+"var "+fieldName+": "+
swiftTypeFor(fieldType, true, false) );
if ( isInterface )
code.append((isStatic ? isFinal ?" { get }" : " { get set }" : "")+"\n");
else {
String fieldArgs = "fieldName: \""+field.getName()+"\", fieldType: \""+jniEncoding(field.getType())+"\", fieldCache: &"+fieldIDVar+
(isStatic?
", className: \""+pathToClass+"\", classCache: &"+classCacheVar :
", object: javaObject");
code.append( " {\n" );
code.append( " get {\n" );
code.append( " let __value = JNIField.Get"+funcType( fieldType, mods )+"Field( "+fieldArgs+" )\n" );
if ( isObjectType( fieldType ) )
code.append( " defer { JNI.DeleteLocalRef( __value ) }\n" );
code.append( " return "+decoder( "__value", fieldType, "" )+"\n" );
code.append( " }\n" );
if (!isFinal) {
code.append(" set(newValue) {\n");
code.append(" var __locals = [jobject]()\n");
code.append(" let __value = " + encoder("newValue", fieldType) + "\n");
code.append(" JNIField.Set" + funcType(fieldType, mods) + "Field( " + fieldArgs
+ ", value: __value" + encodeSuffix(fieldType) + ", locals: &__locals )\n");
code.append(" }\n");
}
code.append( " }\n" );
}
if ( arrayType )
code.append( " #endif\n");
code.append( "\n" );
}
}
void generateConstructors( String pathToClass, String classSuffix, boolean isListenerBase ) {
HashMap<String,Boolean> constructorSeen = new HashMap<String,Boolean>();
java.lang.reflect.Constructor<?> constructors[] = clazz.getDeclaredConstructors();
if ( sortMembers )
java.util.Arrays.sort( constructors, new Comparator<java.lang.reflect.Constructor<?>>() {
@Override
public int compare(java.lang.reflect.Constructor<?> o1, java.lang.reflect.Constructor<?> o2) {
return argsFor( newConstructor(o1), true, true, null )
.compareTo(argsFor( newConstructor(o2), true, true, null ));
}
} );
for (java.lang.reflect.Constructor<?> _constructor : constructors) {
Constructor<?> constructor = newConstructor( _constructor );
int mods = constructor.getModifiers();
progress(constructor);
code.append( " /// "+constructor+"\n\n" );
String namedSignature = argsFor( constructor, true, true, null );
if ( skipBecause( "init", constructor.constructor, new boolean [] {
!Modifier.isPublic(mods) && !Modifier.isProtected(mods),
constructorSeen.containsKey(namedSignature),
ambiguousInitialiser( constructor.toString() )
} ) )
continue;
constructorSeen.put( namedSignature, true );
String methodIDVar = "new_MethodID_"+(++idcount);
java.lang.reflect.Constructor<?> overridden = constructorOverride(_constructor, superclazz);
boolean canThrow = constructor.getExceptionTypes().length != 0 && constructor.getParameterCount() != 0 &&
(overridden == null || overridden.getExceptionTypes().length != 0);
if (overridden != null)
if ( argumentNamesDiffer( constructor, newConstructor( overridden ) ) )
overridden = null;
boolean arrayType = false;
for ( Parameter param : constructor.getParameters() )
if ( crashesCompilerOnLinx( param.getType() ) )
arrayType = true;
if ( arrayType )
code.append( " #if !os(Linux)\n");
code.append(" private static var "+methodIDVar+": jmethodID?\n\n" );
code.append( " public "+/*(overridden != null && !isLost && clazz != String.class || isListenerBase ? "override " : "")+*/
"convenience init("+argsFor( constructor, false, true, null )+")"+(canThrow?" throws":"")+" {\n" );
code.append( functionHeader( constructor.getParameters(), null, isListenerBase ? 1 : 0 ) );
String signature = jniArgs(constructor, "", "");
if ( isListenerBase ) {
signature = jniArgs(constructor, "", "J");
code.append("\n self.init( javaObject: nil )\n");
code.append(" __args["+constructor.getParameterCount()+"] = __local!.swiftValue()\n\n");
}
code.append( " let __object = JNIMethod.NewObject( className: \""+pathToClass+"\", classCache: &"+
classSuffix+"."+classSuffix+"JNIClass, methodSig: \""+signature+"V\", methodCache: &"+classSuffix+"."+methodIDVar+
", args: &__args, locals: &__locals )\n" );
if ( canThrow )
addThrowCode( constructor );
if ( isListenerBase )
code.append( " self.javaObject = __object\n" );
else
code.append( " self.init( javaObject: __object )\n" );
code.append( " JNI.DeleteLocalRef( __object )\n" );
code.append( " }\n" );
String unnamedSigature = argsFor( constructor, true, false, null );
if ( !constructorSeen.containsKey(unnamedSigature) && constructor.getParameters().length != 0 ) {
code.append( "\n public "+/*(unnamedOverride && !isLost && clazz != String.class || isListenerBase ? "override " : "")+*/
"convenience init("+argsFor( constructor, false, false, null )+")"+(canThrow?" throws":"")+" {\n" );
code.append( " "+(canThrow?"try ":"")+"self.init("+passthroughArguments(constructor,null, "_")+" )\n }\n" );
constructorSeen.put( unnamedSigature, true );
}
if ( arrayType )
code.append( " #endif\n");
code.append( "\n" );
}
}
boolean generateMethods( java.lang.reflect.Method methods[], boolean isProtocol, HashMap<String,Boolean> fieldsSeen, String outputClassName, boolean isListenerBase ) {
HashMap<String,Boolean> methodsSeen = new HashMap<String,Boolean>();
boolean hasSubclassResponsibility = false;
if ( sortMembers )
java.util.Arrays.sort( methods, new Comparator<java.lang.reflect.Method>() {
@Override
public int compare(java.lang.reflect.Method o1, java.lang.reflect.Method o2) {
int statics = compareStatic( o1.getModifiers(), o2.getModifiers() );
return statics != 0 ? statics : swiftSignatureFor( newMethod(o1), isProtocol, true, true, null)
.compareTo(swiftSignatureFor( newMethod(o2), isProtocol, true, true, null));
}
} );
for (java.lang.reflect.Method _method : methods ) {
Method method = newMethod( _method );
int mods = method.getModifiers();
boolean isStatic = Modifier.isStatic(mods);
progress(method);
code.append( " /// "+method+"\n\n" );
if ( subclassResponsibilities.containsKey(method.toString()) )
hasSubclassResponsibility = true;
java.lang.reflect.Method overridden = funcOverride(method.method, superclazz);
if ( overridden != null && Modifier.isPrivate(overridden.getModifiers()) )
overridden = null;
boolean unnamedOverride = overridden != null;
if ( argumentNamesDiffer(method, newMethod(overridden)) )
overridden = null;
unnamedOverride = overridden != null;
String methodName = method.getName();
String methodString = method.toString();
boolean fieldExists = fieldsSeen.containsKey(safe(methodName)) && method.getParameterCount() == 0;
if ( skipBecause( "method", method.method, new boolean [] {
!Modifier.isPublic(mods) && !Modifier.isProtected(mods),
overridden != null && !isStatic && !isListenerBase && !isUnavailable(superclazz)
&& !(isInterface && clazz.getInterfaces().length != 0
&& isUnavailable(clazz.getInterfaces()[0])),
isInterface && (dontEnforceProtocol(clazz)
|| awkwardMethodInProtocol(method)
|| isUnavailable(method.getReturnType())),
methodName.startsWith("lambda$"),
fieldExists
} ) && !methodString.equals("public void javax.swing.text.PlainDocument.insertString(int,java.lang.String,javax.swing.text.AttributeSet) throws javax.swing.text.BadLocationException")
&& !methodString.equals("public java.util.Set java.util.HashMap.keySet()") )
continue;
String namedSignature = swiftSignatureFor( method, isProtocol, true, true, null);
if ( methodsSeen.containsKey(namedSignature) )
continue;
methodsSeen.put(namedSignature, true );
Class <?> returnType = method.getReturnType();
boolean arrayType = crashesCompilerOnLinx( method );
boolean canThrow = method.getExceptionTypes().length != 0;
String unnamedSignature = swiftSignatureFor( method, isProtocol, true, false, null);
boolean createsNameless = !methodsSeen.containsKey(unnamedSignature) && !fieldExists &&
!(isInterface && lostType(returnType)) && method.getParameterCount() != 0 && !isListenerBase;
if ( arrayType )
code.append( " #if !os(Linux)\n");
if ( isProtocol && isStatic )
code.append(" //");
String methodKey = methodKey(method);
Method interfaceMethod = interfaceMethods.get(methodKey);
interfaceMethods.remove(methodKey);
boolean createBody = !isListenerBase || !isInterface;
boolean notVoid = notVoid(returnType);
if ( !(isProtocol && argumentsOfProtocolRenamed( clazz )) ) {
String methodIDVar = methodName+"_MethodID_"+(++idcount), methodIDVarRef = methodIDVar;
if ( !isStatic )
methodIDVarRef = outputClassName+"."+methodIDVarRef;
if ( !isProtocol && (!isListenerBase || !isInterface) )
code.append(" private static var "+methodIDVar+": jmethodID?\n\n" );
code.append(" " + (overridden != null && !isLost && !createBody && !(isListenerBase && isProtocol)
|| isAdapter() && isListenerBase ? "override " : "")
+ swiftSignatureFor(method, isProtocol, false, true, interfaceMethod));
if ( isListenerBase )
code.append( " /**/" );
if (isProtocol)
code.append("\n");
else if (isEnum) {
code.append(" {\n return "+(canThrow?"try ":"")+(isStatic ? classSuffix+"Forward." : "underlier()."));
code.append(safe(method.getName()) + "("+passthroughArguments(method, interfaceMethod, "")+" )\n }\n");
}
else {
code.append(" {\n");
if ( createBody ) {
code.append( functionHeader( method.getParameters(), interfaceMethod, 0 ) );
code.append( " " );
if ( notVoid )
code.append( "let __return = " );
String methodArgs =
(Modifier.isStatic(mods)?
"className: \""+pathToClass+"\", classCache: &"+classCacheVar :
"object: javaObject")+
", methodName: \""+methodName+"\", methodSig: \""+jniSignature(method, "", "")+"\", methodCache: &"+methodIDVarRef;
code.append( "JNIMethod.Call"+funcType( returnType, mods )+"Method( "+methodArgs + ", args: &__args, locals: &__locals )\n" );
if ( isObjectType( returnType ) )
code.append( " defer { JNI.DeleteLocalRef( __return ) }\n" );
if ( canThrow )
addThrowCode( method );
if ( notVoid )
code.append(" return "+decoder( "__return", returnType, "")+"\n");
}
else if ( notVoid(returnType) ) {
String passthrough = "";
for ( Parameter param : method.getParameters() )
passthrough += (passthrough==""?" ":", ")+safe(param.getName())+": _"+safe(param.getName());
code.append(" return "+ (clazz.isInterface() ? defaultReturn(returnType) :
"super."+methodName+"("+passthrough+" )")+"\n");
}
code.append(" }\n\n");
}
}
if ( createsNameless && !isProtocol ) {
if ( isProtocol && isStatic )
code.append("//");
code.append(" " + (unnamedOverride && !isLost && !createBody || isAdapter() && isListenerBase ? "override " : "")
+ swiftSignatureFor(method, isProtocol, false, false, interfaceMethod));
if ( isListenerBase )
code.append( " /**/" );
if (isProtocol)
code.append("\n");
else {
code.append(" {\n");
code.append(" "+(notVoid?"return ":"") + (canThrow?"try ":"") +
safe(method.getName()) + "("+passthroughArguments(method, interfaceMethod, "_")+" )\n");
code.append(" }\n" );
}
}
if ( arrayType )
code.append( " #endif\n");
code.append( "\n" );
methodsSeen.put( unnamedSignature, true );
}
return hasSubclassResponsibility;
}
void generateCallbackBase( HashMap<String,Boolean> fieldsSeen, java.lang.reflect.Method responsibles[] ) throws IOException {
java.lang.reflect.Method methods[] = responsibles.length != 0 ? responsibles : clazz.getMethods();
ArrayList<java.lang.reflect.Method> methodsCallingBack = new ArrayList<java.lang.reflect.Method>();
if ( sortMembers )
java.util.Arrays.sort( methods, new Comparator<java.lang.reflect.Method>() {
@Override
public int compare(java.lang.reflect.Method o1, java.lang.reflect.Method o2) {
int statics = compareStatic( o1.getModifiers(), o2.getModifiers() );
return statics != 0 ? statics : swiftSignatureFor( newMethod(o1), true, true, true, null)
.compareTo(swiftSignatureFor( newMethod(o2), true, true, true, null));
}
} );
for (int i = 0; i < methods.length; i++) {
Method method = newMethod( methods[i] );
if ( skipCallbackMethod( method ) )
continue;
if ( crashesCompilerOnLinx( method ) )
code.append("#if !os(Linux)\n");
methodsCallingBack.add( method.method );
code.append("private typealias " + jniName(method, i) + "_type = @convention(c) "
+ jniDecl(method, null) + "\n\n");
code.append("private func " + jniName(method, i) + jniDecl(method, "_ ") + " {\n");
String passthrough = "";
for (Parameter param : method.getParameters())
passthrough += (passthrough == ""?" ":", ") + safe(param.getName())+": " +/////
decoder( safe(param.getName()), param.getType(), ", consume: false" );//+(!p.getType().isPrimitive()?"!":"");
String call = classSuffix + "Local_.swiftObject( jniEnv: __env, javaObject: __this, swiftObject: __swiftObject )."
+ method.getName() + "(" + passthrough + " )";
boolean rethrow = method.getExceptionTypes().length != 0;
String indent = "";
if ( rethrow ) {
call = "try " + call;
code.append(" do {\n");
indent = " ";
}
Class<?> returnType = method.getReturnType();
boolean notVoid = notVoid(returnType);
if ( notVoid )
call = "let __return = "+call;
code.append(indent+" "+call+"\n");
if ( notVoid ) {