-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathJavaClassTranslator.swift
More file actions
984 lines (841 loc) · 33.3 KB
/
JavaClassTranslator.swift
File metadata and controls
984 lines (841 loc) · 33.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import JavaKit
import JavaKitReflection
import SwiftSyntax
/// Utility type that translates a single Java class into its corresponding
/// Swift type and any additional helper types or functions.
struct JavaClassTranslator {
/// The translator we are working with, which provides global knowledge
/// needed for translation.
let translator: JavaTranslator
/// The Java class (or interface) being translated.
let javaClass: JavaClass<JavaObject>
/// Whether to translate this Java class into a Swift class.
///
/// This will be false for Java interfaces.
let translateAsClass: Bool
/// The type parameters to the Java class or interface.
let javaTypeParameters: [TypeVariable<JavaClass<JavaObject>>]
/// The set of nested classes of this class that will be rendered along
/// with it.
let nestedClasses: [JavaClass<JavaObject>]
/// The full name of the Swift type that will be generated for this Java
/// class.
let swiftTypeName: String
/// The effective Java superclass object, which is the nearest
/// superclass that has been mapped into Swift.
let effectiveJavaSuperclass: JavaClass<JavaObject>?
/// The Swift name of the superclass.
let swiftSuperclass: String?
/// The Swift names of the interfaces that this class implements.
let swiftInterfaces: [String]
/// The annotations of the Java class
let annotations: [Annotation]
/// The (instance) fields of the Java class.
var fields: [Field] = []
/// The static fields of the Java class.
var staticFields: [Field] = []
/// Enum constants of the Java class, which are also static fields and are
/// reflected additionally as enum cases.
var enumConstants: [Field] = []
/// Constructors of the Java class.
var constructors: [Constructor<JavaObject>] = []
/// The (instance) methods of the Java class.
var methods: MethodCollector = MethodCollector()
/// The static methods of the Java class.
var staticMethods: MethodCollector = MethodCollector()
/// The native instance methods of the Java class, which are also reflected
/// in a `*NativeMethods` protocol so they can be implemented in Swift.
var nativeMethods: [Method] = []
/// The native static methods of the Java class.
/// TODO: These are currently unimplemented.
var nativeStaticMethods: [Method] = []
/// Whether the Java class we're translating is actually an interface.
var isInterface: Bool {
return javaClass.isInterface()
}
/// The name of the enclosing Swift type, if there is one.
var swiftParentType: String? {
swiftTypeName.splitSwiftTypeName().parentType
}
/// The name of the innermost Swift type, without the enclosing type.
var swiftInnermostTypeName: String {
swiftTypeName.splitSwiftTypeName().name
}
/// The generic parameter clause for the Swift version of the Java class.
var genericParameterClause: String {
if javaTypeParameters.isEmpty {
return ""
}
let genericParameters = javaTypeParameters.map { param in
"\(param.getName()): AnyJavaObject"
}
return "<\(genericParameters.joined(separator: ", "))>"
}
/// Prepare translation for the given Java class (or interface).
init(javaClass: JavaClass<JavaObject>, translator: JavaTranslator) throws {
let fullName = javaClass.getName()
self.javaClass = javaClass
self.translator = translator
self.translateAsClass = translator.translateAsClass && !javaClass.isInterface()
self.swiftTypeName = try translator.getSwiftTypeNameFromJavaClassName(
fullName,
preferValueTypes: false,
escapeMemberNames: false
)
// Type parameters.
self.javaTypeParameters = javaClass.getTypeParameters().compactMap { $0 }
self.nestedClasses = translator.nestedClasses[fullName] ?? []
// Superclass.
if !javaClass.isInterface() {
var javaSuperclass = javaClass.getSuperclass()
var swiftSuperclass: String? = nil
while let javaSuperclassNonOpt = javaSuperclass {
do {
swiftSuperclass = try translator.getSwiftTypeName(javaSuperclassNonOpt, preferValueTypes: false).swiftName
break
} catch {
translator.logUntranslated("Unable to translate '\(fullName)' superclass: \(error)")
}
javaSuperclass = javaSuperclassNonOpt.getSuperclass()
}
self.effectiveJavaSuperclass = javaSuperclass
self.swiftSuperclass = swiftSuperclass
} else {
self.effectiveJavaSuperclass = nil
self.swiftSuperclass = nil
}
// Interfaces.
self.swiftInterfaces = javaClass.getGenericInterfaces().compactMap { (javaType) -> String? in
guard let javaType else {
return nil
}
do {
let typeName = try translator.getSwiftTypeNameAsString(
javaType,
preferValueTypes: false,
outerOptional: .nonoptional
)
return "\(typeName)"
} catch {
translator.logUntranslated("Unable to translate '\(fullName)' interface '\(javaType.getTypeName())': \(error)")
return nil
}
}
self.annotations = javaClass.getAnnotations().compactMap(\.self)
// Collect all of the class members that we will need to translate.
// TODO: Switch over to "declared" versions of these whenever we don't need
// to see inherited members.
// Gather fields.
for field in javaClass.getFields() {
guard let field else { continue }
addField(field)
}
// Gather constructors.
for constructor in javaClass.getConstructors() {
guard let constructor else { continue }
addConstructor(constructor)
}
// Gather methods.
let methods = translateAsClass
? javaClass.getDeclaredMethods()
: javaClass.getMethods()
for method in methods {
guard let method else { continue }
// Only look at public and protected methods here.
guard method.isPublic || method.isProtected else { continue }
// Skip any methods that are expected to be implemented in Swift. We will
// visit them in the second pass, over the *declared* methods, because
// we want to see non-public methods as well.
let implementedInSwift = method.isNative &&
method.getDeclaringClass()!.equals(javaClass.as(JavaObject.self)!) &&
translator.swiftNativeImplementations.contains(javaClass.getName())
if implementedInSwift {
continue
}
addMethod(method, isNative: false)
}
if translator.swiftNativeImplementations.contains(javaClass.getName()) {
// Gather the native methods we're going to implement.
for method in javaClass.getDeclaredMethods() {
guard let method else { continue }
// Only visit native methods in this second pass.
if !method.isNative {
continue
}
addMethod(method, isNative: true)
}
}
}
}
/// MARK: Collection of Java class members.
extension JavaClassTranslator {
/// Add a field to the appropriate lists(s) for later translation.
private mutating func addField(_ field: Field) {
// Static fields go into a separate list.
if field.isStatic {
staticFields.append(field)
// Enum constants will be used to produce a Swift enum projecting the
// Java enum.
if field.isEnumConstant() {
enumConstants.append(field)
}
return
}
// Don't include inherited fields when translating to a class.
if translateAsClass &&
!field.getDeclaringClass()!.equals(javaClass.as(JavaObject.self)!) {
return
}
fields.append(field)
}
/// Add a constructor to the list of constructors for later translation.
private mutating func addConstructor(_ constructor: Constructor<JavaObject>) {
constructors.append(constructor)
}
/// Add a method to the appropriate list for later translation.
private mutating func addMethod(_ method: Method, isNative: Bool) {
switch (method.isStatic, isNative) {
case (false, false): methods.add(method)
case (true, false): staticMethods.add(method)
case (false, true): nativeMethods.append(method)
case (true, true): nativeStaticMethods.append(method)
}
}
}
/// MARK: Rendering of Java class members as Swift declarations.
extension JavaClassTranslator {
/// Render the Swift declarations that will express this Java class in Swift.
package func render() -> [DeclSyntax] {
var allDecls: [DeclSyntax] = []
allDecls.append(renderPrimaryType())
allDecls.append(contentsOf: renderNestedClasses())
if let staticMemberExtension = renderStaticMemberExtension() {
allDecls.append(staticMemberExtension)
}
if let nativeMethodsProtocol = renderNativeMethodsProtocol() {
allDecls.append(nativeMethodsProtocol)
}
allDecls.append(contentsOf: renderAnnotationExtensions())
return allDecls
}
/// Render the declaration for the main part of the Java class, which
/// includes the constructors, non-static fields, and non-static methods.
private func renderPrimaryType() -> DeclSyntax {
// Render all of the instance fields as Swift properties.
let properties = fields.compactMap { field in
do {
return try renderField(field)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' static field '\(field.getName())': \(error)")
return nil
}
}
// Declarations used to capture Java enums.
let enumDecls: [DeclSyntax] = renderEnum(name: "\(swiftInnermostTypeName)Cases")
// Render all of the constructors as Swift initializers.
let initializers = constructors.compactMap { constructor in
do {
return try renderConstructor(constructor)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' constructor: \(error)")
return nil
}
}
// Render all of the instance methods in Swift.
let instanceMethods = methods.methods.compactMap { method in
do {
return try renderMethod(method, implementedInSwift: false, renderFailureAsBestEffortUnavailableDecl: true)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' method '\(method.getName())': \(error)")
return nil
}
}
// Collect all of the members of this type.
let members = properties + enumDecls + initializers + instanceMethods
// Compute the "extends" clause for the superclass (of the struct
// formulation) or the inheritance clause (for the class
// formulation).
let extends: String
let inheritanceClause: String
if translateAsClass {
extends = ""
inheritanceClause = swiftSuperclass.map { ": \($0)" } ?? ""
} else {
extends = swiftSuperclass.map { ", extends: \($0).self" } ?? ""
inheritanceClause = ""
}
// Compute the string to capture all of the interfaces.
let interfacesStr: String
if swiftInterfaces.isEmpty {
interfacesStr = ""
} else {
let prefix = javaClass.isInterface() ? "extends" : "implements"
interfacesStr = ", \(prefix): \(swiftInterfaces.map { "\($0).self" }.joined(separator: ", "))"
}
// Emit the struct declaration describing the java class.
let classOrInterface: String = isInterface ? "JavaInterface" : "JavaClass";
let introducer = translateAsClass ? "open class" : "public struct"
var classDecl: DeclSyntax =
"""
@\(raw: classOrInterface)(\(literal: javaClass.getName())\(raw: extends)\(raw: interfacesStr))
\(raw: introducer) \(raw: swiftInnermostTypeName)\(raw: genericParameterClause)\(raw: inheritanceClause) {
\(raw: members.map { $0.description }.joined(separator: "\n\n"))
}
"""
// If there is a parent type, wrap this type up in an extension of that
// parent type.
if let swiftParentType {
classDecl =
"""
extension \(raw: swiftParentType) {
\(classDecl)
}
"""
}
// Format the class declaration.
return classDecl.formatted(using: translator.format).cast(DeclSyntax.self)
}
/// Render any nested classes that will not be rendered separately.
func renderNestedClasses() -> [DeclSyntax] {
return nestedClasses
.sorted {
$0.getName() < $1.getName()
}.compactMap { clazz in
do {
return try translator.translateClass(clazz)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' nested class '\(clazz.getName())': \(error)")
return nil
}
}.flatMap(\.self)
}
/// Render the extension of JavaClass that collects all of the static
/// fields and methods.
package func renderStaticMemberExtension() -> DeclSyntax? {
// Determine the where clause we need for static methods.
let staticMemberWhereClause: String
if !javaTypeParameters.isEmpty {
let genericParameterNames = javaTypeParameters.compactMap { typeVar in
typeVar.getName()
}
let genericArgumentClause = "<\(genericParameterNames.joined(separator: ", "))>"
staticMemberWhereClause = " where ObjectType == \(swiftTypeName)\(genericArgumentClause)"
} else {
staticMemberWhereClause = ""
}
// Render static fields.
let properties = staticFields.compactMap { field in
// Translate each static field.
do {
return try renderField(field)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' field '\(field.getName())': \(error)")
return nil
}
}
// Render static methods.
let methods = staticMethods.methods.compactMap { method in
// Translate each static method.
do {
return try renderMethod(
method, implementedInSwift: /*FIXME:*/false,
genericParameterClause: genericParameterClause,
whereClause: staticMemberWhereClause
)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' static method '\(method.getName())': \(error)")
return nil
}
}
// Gather all of the members.
let members = properties + methods
if members.isEmpty {
return nil
}
// Specify the specialization arguments when needed.
let extSpecialization: String
if genericParameterClause.isEmpty {
extSpecialization = "<\(swiftTypeName)>"
} else {
extSpecialization = ""
}
let extDecl: DeclSyntax =
"""
extension JavaClass\(raw: extSpecialization) {
\(raw: members.map { $0.description }.joined(separator: "\n\n"))
}
"""
return extDecl.formatted(using: translator.format).cast(DeclSyntax.self)
}
/// Render the protocol used for native methods.
func renderNativeMethodsProtocol() -> DeclSyntax? {
guard translator.swiftNativeImplementations.contains(javaClass.getName()) else {
return nil
}
let nativeMembers = nativeMethods.compactMap { method in
do {
return try renderMethod(
method,
implementedInSwift: true,
)
} catch {
translator.logUntranslated("Unable to translate '\(javaClass.getName())' method '\(method.getName())': \(error)")
return nil
}
}
if nativeMembers.isEmpty {
return nil
}
let protocolDecl: DeclSyntax =
"""
/// Describes the Java `native` methods for ``\(raw: swiftTypeName)``.
///
/// To implement all of the `native` methods for \(raw: swiftTypeName) in Swift,
/// extend \(raw: swiftTypeName) to conform to this protocol and mark
/// each implementation of the protocol requirement with
/// `@JavaMethod`.
protocol \(raw: swiftTypeName)NativeMethods {
\(raw: nativeMembers.map { $0.description }.joined(separator: "\n\n"))
}
"""
return protocolDecl.formatted(using: translator.format).cast(DeclSyntax.self)
}
func renderAnnotationExtensions() -> [DeclSyntax] {
var extensions: [DeclSyntax] = []
for annotation in annotations {
let annotationName = annotation.annotationType().getName().splitSwiftTypeName().name
if annotationName == "ThreadSafe" || annotationName == "Immutable" { // If we are threadsafe, mark as unchecked Sendable
extensions.append(
"""
extension \(raw: swiftTypeName): @unchecked Swift.Sendable { }
"""
)
} else if annotationName == "NotThreadSafe" { // If we are _not_ threadsafe, mark sendable unavailable
extensions.append(
"""
@available(unavailable, *)
extension \(raw: swiftTypeName): Swift.Sendable { }
"""
)
}
}
return extensions
}
/// Render the given Java constructor as a Swift initializer.
package func renderConstructor(
_ javaConstructor: Constructor<some AnyJavaObject>
) throws -> DeclSyntax {
var errors = TranslationErrorCollector(bestEffortRecover: false)
let parameters = try translateParameters(javaConstructor.getParameters(), translationErrors: &errors) + ["environment: JNIEnvironment? = nil"]
let parametersStr = parameters.map { $0.description }.joined(separator: ", ")
let throwsStr = javaConstructor.throwsCheckedException ? "throws" : ""
let accessModifier = javaConstructor.isPublic ? "public " : ""
let convenienceModifier = translateAsClass ? "convenience " : ""
let nonoverrideAttribute = translateAsClass ? "@_nonoverride " : ""
return """
/**
\(raw: errors.doccCommentsText)
*/
@JavaMethod
\(raw: errors.unavailableDueToImportErrorsText)
\(raw: nonoverrideAttribute)\(raw: accessModifier)\(raw: convenienceModifier)init(\(raw: parametersStr))\(raw: throwsStr)
"""
}
/// Translates the given Java method into a Swift declaration.
package func renderMethod(
_ javaMethod: Method,
implementedInSwift: Bool,
genericParameterClause: String = "",
whereClause: String = "",
renderFailureAsBestEffortUnavailableDecl: Bool = false
) throws -> DeclSyntax {
var errors = TranslationErrorCollector(bestEffortRecover: renderFailureAsBestEffortUnavailableDecl)
// Map the parameters.
let parameters = try translateParameters(javaMethod.getParameters(), translationErrors: &errors)
let parametersStr = parameters.map { $0.description }.joined(separator: ", ")
// Map the result type.
let resultTypeStr: String
let resultType = try translator.getSwiftTypeNameAsString(
javaMethod.getGenericReturnType()!,
preferValueTypes: true,
outerOptional: .implicitlyUnwrappedOptional
)
// FIXME: cleanup the checking here
if resultType != "Void" && resultType != "Swift.Void" {
resultTypeStr = " -> \(resultType)"
} else {
resultTypeStr = ""
}
let throwsStr = javaMethod.throwsCheckedException ? "throws" : ""
let swiftMethodName = javaMethod.getName().escapedSwiftName
let methodAttribute: AttributeSyntax = implementedInSwift
? ""
: javaMethod.isStatic ? "@JavaStaticMethod\n" : "@JavaMethod\n";
let accessModifier = implementedInSwift ? ""
: (javaMethod.isStatic || !translateAsClass) ? "public "
: "open "
let overrideOpt = (translateAsClass && !javaMethod.isStatic && isOverride(javaMethod))
? "override "
: ""
if resultType.optionalWrappedType() != nil || parameters.contains(where: { $0.type.trimmedDescription.optionalWrappedType() != nil }) {
let parameters = parameters.map { param -> (clause: FunctionParameterSyntax, passedArg: String) in
let name = param.secondName!.trimmedDescription
return if let optionalType = param.type.trimmedDescription.optionalWrappedType() {
(clause: "_ \(raw: name): \(raw: optionalType)", passedArg: "\(name).toJavaOptional()")
} else {
(clause: param, passedArg: "\(name)")
}
}
let resultOptional: String = resultType.optionalWrappedType() ?? resultType
let baseBody: ExprSyntax = "\(raw: javaMethod.throwsCheckedException ? "try " : "")\(raw: swiftMethodName)(\(raw: parameters.map(\.passedArg).joined(separator: ", ")))"
let body: ExprSyntax = if let optionalType = resultType.optionalWrappedType() {
"Optional(javaOptional: \(baseBody))"
} else {
baseBody
}
return """
\(raw: errors.doccCommentsText)
\(raw: errors.unavailableDueToImportErrorsText)
\(methodAttribute)\(raw: accessModifier)\(raw: overrideOpt)func \(raw: swiftMethodName)\(raw: genericParameterClause)(\(raw: parametersStr))\(raw: throwsStr)\(raw: resultTypeStr)\(raw: whereClause)
\(raw: accessModifier)\(raw: overrideOpt)func \(raw: swiftMethodName)Optional\(raw: genericParameterClause)(\(raw: parameters.map(\.clause.description).joined(separator: ", ")))\(raw: throwsStr) -> \(raw: resultOptional)\(raw: whereClause) {
\(body)
}
"""
} else {
return """
\(raw: errors.doccCommentsText)
\(raw: errors.unavailableDueToImportErrorsText)
\(methodAttribute)\(raw: accessModifier)\(raw: overrideOpt)func \(raw: swiftMethodName)\(raw: genericParameterClause)(\(raw: parametersStr))\(raw: throwsStr)\(raw: resultTypeStr)\(raw: whereClause)
"""
}
}
/// Render a single Java field into the corresponding Swift property, or
/// throw an error if that is not possible for any reason.
package func renderField(_ javaField: Field) throws -> DeclSyntax {
let typeName = try translator.getSwiftTypeNameAsString(
javaField.getGenericType()!,
preferValueTypes: true,
outerOptional: .implicitlyUnwrappedOptional
)
let fieldAttribute: AttributeSyntax = javaField.isStatic ? "@JavaStaticField" : "@JavaField";
let swiftFieldName = javaField.getName().escapedSwiftName
if let optionalType = typeName.optionalWrappedType() {
let setter = if !javaField.isFinal {
"""
set {
\(swiftFieldName) = newValue.toJavaOptional()
}
"""
} else {
""
}
return """
\(fieldAttribute)(isFinal: \(raw: javaField.isFinal))
public var \(raw: swiftFieldName): \(raw: typeName)
public var \(raw: swiftFieldName)Optional: \(raw: optionalType) {
get {
Optional(javaOptional: \(raw: swiftFieldName))
}\(raw: setter)
}
"""
} else {
return """
\(fieldAttribute)(isFinal: \(raw: javaField.isFinal))
public var \(raw: swiftFieldName): \(raw: typeName)
"""
}
}
package func renderEnum(name: String) -> [DeclSyntax] {
if enumConstants.isEmpty {
return []
}
let extensionSyntax: DeclSyntax = """
public enum \(raw: name): Equatable {
\(raw: enumConstants.map { "case \($0.getName())" }.joined(separator: "\n"))
}
"""
let mappingSyntax: DeclSyntax = """
public var enumValue: \(raw: name)! {
let classObj = self.javaClass
\(raw: enumConstants.map {
// The equals method takes a java object, so we need to cast it here
"""
if self.equals(classObj.\($0.getName())?.as(JavaObject.self)) {
return \(name).\($0.getName())
}
"""
}.joined(separator: " else ")) else {
return nil
}
}
"""
let convenienceModifier = translateAsClass ? "convenience " : ""
let initSyntax: DeclSyntax = """
public \(raw: convenienceModifier)init(_ enumValue: \(raw: name), environment: JNIEnvironment? = nil) {
let _environment = if let environment {
environment
} else {
try! JavaVirtualMachine.shared().environment()
}
let classObj = try! JavaClass<\(raw: swiftInnermostTypeName)>(environment: _environment)
switch enumValue {
\(raw: enumConstants.map {
return """
case .\($0.getName()):
if let \($0.getName()) = classObj.\($0.getName()) {
\(translateAsClass
? "self.init(javaHolder: \($0.getName()).javaHolder)"
: "self = \($0.getName())")
} else {
fatalError("Enum value \($0.getName()) was unexpectedly nil, please re-run Java2Swift on the most updated Java class")
}
"""
}.joined(separator: "\n"))
}
}
"""
return [extensionSyntax, mappingSyntax, initSyntax]
}
// Translate a Java parameter list into Swift parameters.
private func translateParameters(_ parameters: [Parameter?], translationErrors: inout TranslationErrorCollector) throws -> [FunctionParameterSyntax] {
return try parameters.compactMap { (javaParameter) -> (FunctionParameterSyntax?) in
guard let javaParameter else { return nil }
let typeName: String
do {
typeName = try translator.getSwiftTypeNameAsString(
javaParameter.getParameterizedType()!,
preferValueTypes: true,
outerOptional: .optional
)
} catch {
translationErrors.record("Failed to convert parameter '\(javaParameter.getName())' type '\(javaParameter.getParameterizedType()!) to Swift'")
typeName = "SwiftJavaFailedImportType" // best-effort placeholder
}
let paramName = javaParameter.getName()
return "_ \(raw: paramName): \(raw: typeName)"
}
}
}
package struct TranslationErrorCollector {
package let bestEffortRecover: Bool
private var errors: [String] = []
package var doccCommentsText: String {
guard errors.count > 0 else {
return ""
}
return """
///
/// ### Swift-Java import errors
///
/// * \(errors.joined(separator: "\n /// * "))
"""
}
package var unavailableDueToImportErrorsText: String {
guard errors.count > 0 else {
return ""
}
return """
@available(*, unavailable, message: "swift-java was unable to import this method. See doc comments for import error details.")
"""
}
mutating func record(_ errorMessage: String) {
errors.append(errorMessage)
}
package init(bestEffortRecover: Bool) {
self.bestEffortRecover = bestEffortRecover
}
}
/// Helper struct that collects methods, removing any that have been overridden
/// by a covariant method.
struct MethodCollector {
var methods: [Method] = []
/// Mapping from method names to the indices of each method within the
/// list of methods.
var methodsByName: [String: [Int]] = [:]
/// Add this method to the collector.
mutating func add(_ method: Method) {
// Compare against existing methods with this same name.
for existingMethodIndex in methodsByName[method.getName()] ?? [] {
let existingMethod = methods[existingMethodIndex]
switch MethodVariance(method, existingMethod) {
case .equivalent, .unrelated:
// Nothing to do.
continue
case .contravariantResult:
// This method is worse than what we have; there is nothing to do.
return
case .covariantResult:
// This method is better than the one we have; replace the one we
// have with it.
methods[existingMethodIndex] = method
return
}
}
// If we get here, there is no related method in the list. Add this
// new method.
methodsByName[method.getName(), default: []].append(methods.count)
methods.append(method)
}
}
// MARK: Utility functions
extension JavaClassTranslator {
/// Determine whether this method is an override of another Java
/// method.
func isOverride(_ method: Method) -> Bool {
var currentSuperclass = effectiveJavaSuperclass
while let currentSuperclassNonOpt = currentSuperclass {
// Set the loop up for the next run.
defer {
currentSuperclass = currentSuperclassNonOpt.getSuperclass()
}
do {
// If this class didn't get translated into Swift, skip it.
if translator.translatedClasses[currentSuperclassNonOpt.getName()] == nil {
continue
}
// If this superclass declares a method with the same parameter types,
// we have an override.
guard let overriddenMethod = try currentSuperclassNonOpt
.getDeclaredMethod(method.getName(), method.getParameterTypes()) else {
continue
}
// Ignore non-public, non-protected methods because they would not
// have been render into the Swift superclass.
if !overriddenMethod.isPublic && !overriddenMethod.isProtected {
continue
}
// We know that Java considers this method an override. However, it is
// possible that Swift will not consider it an override, because Java
// has subtyping relations that Swift does not.
if method.getGenericReturnType().isEqualToOrSubtypeOf(overriddenMethod.getGenericReturnType()) {
return true
}
} catch {
}
}
return false
}
}
extension [Type?] {
/// Determine whether the types in the array match the other array.
func allTypesEqual(_ other: [Type?]) -> Bool {
if self.count != other.count {
return false
}
for (selfType, otherType) in zip(self, other) {
if !selfType!.isEqualTo(otherType!) {
return false
}
}
return true
}
}
extension Type {
/// Adjust the given type to use its bounds, mirroring what we do in
/// mapping Java types into Swift.
func adjustToJavaBounds(adjusted: inout Bool) -> Type {
if let typeVariable = self.as(TypeVariable<GenericDeclaration>.self),
typeVariable.getBounds().count == 1,
let bound = typeVariable.getBounds()[0] {
adjusted = true
return bound
}
if let wildcardType = self.as(WildcardType.self),
wildcardType.getUpperBounds().count == 1,
let bound = wildcardType.getUpperBounds()[0] {
adjusted = true
return bound
}
return self
}
/// Determine whether this type is equivalent to or a subtype of the other
/// type.
func isEqualTo(_ other: Type) -> Bool {
// First, adjust types to their bounds, if we need to.
var anyAdjusted: Bool = false
let adjustedSelf = self.adjustToJavaBounds(adjusted: &anyAdjusted)
let adjustedOther = other.adjustToJavaBounds(adjusted: &anyAdjusted)
if anyAdjusted {
return adjustedSelf.isEqualTo(adjustedOther)
}
// If both are classes, check for equivalence.
if let selfClass = self.as(JavaClass<JavaObject>.self),
let otherClass = other.as(JavaClass<JavaObject>.self) {
return selfClass.equals(otherClass.as(JavaObject.self))
}
// If both are arrays, check that their component types are equivalent.
if let selfArray = self.as(GenericArrayType.self),
let otherArray = other.as(GenericArrayType.self) {
return selfArray.getGenericComponentType().isEqualTo(otherArray.getGenericComponentType())
}
// If both are parameterized types, check their raw type and type
// arguments for equivalence.
if let selfParameterizedType = self.as(ParameterizedType.self),
let otherParameterizedType = other.as(ParameterizedType.self) {
if !selfParameterizedType.getRawType().isEqualTo(otherParameterizedType.getRawType()) {
return false
}
return selfParameterizedType.getActualTypeArguments()
.allTypesEqual(otherParameterizedType.getActualTypeArguments())
}
// If both are type variables, compare their bounds.
// FIXME: This is a hack.
if let selfTypeVariable = self.as(TypeVariable<GenericDeclaration>.self),
let otherTypeVariable = other.as(TypeVariable<GenericDeclaration>.self) {
return selfTypeVariable.getBounds().allTypesEqual(otherTypeVariable.getBounds())
}
// If both are wildcards, compare their upper and lower bounds.
if let selfWildcard = self.as(WildcardType.self),
let otherWildcard = other.as(WildcardType.self) {
return selfWildcard.getUpperBounds().allTypesEqual(otherWildcard.getUpperBounds())
&& selfWildcard.getLowerBounds().allTypesEqual(otherWildcard.getLowerBounds())
}
return false
}
/// Determine whether this type is equivalent to or a subtype of the
/// other type.
func isEqualToOrSubtypeOf(_ other: Type) -> Bool {
// First, adjust types to their bounds, if we need to.
var anyAdjusted: Bool = false
let adjustedSelf = self.adjustToJavaBounds(adjusted: &anyAdjusted)
let adjustedOther = other.adjustToJavaBounds(adjusted: &anyAdjusted)
if anyAdjusted {
return adjustedSelf.isEqualToOrSubtypeOf(adjustedOther)
}
if isEqualTo(other) {
return true
}
// If both are classes, check for subclassing.
if let selfClass = self.as(JavaClass<JavaObject>.self),
let otherClass = other.as(JavaClass<JavaObject>.self) {
// If either is a Java array, then this cannot be a subtype relationship
// in Swift.
if selfClass.isArray() || otherClass.isArray() {
return false
}
return selfClass.isSubclass(of: otherClass)
}
// Anything object-like is a subclass of java.lang.Object
if let otherClass = other.as(JavaClass<JavaObject>.self),
otherClass.getName() == "java.lang.Object" {
if self.is(GenericArrayType.self) || self.is(ParameterizedType.self) ||
self.is(WildcardType.self) || self.is(TypeVariable<GenericDeclaration>.self) {
return true
}
}
return false
}
}