forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaClassTranslator.swift
More file actions
1306 lines (1135 loc) · 45.7 KB
/
JavaClassTranslator.swift
File metadata and controls
1306 lines (1135 loc) · 45.7 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
//===----------------------------------------------------------------------===//
//
// 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 JavaLangReflect
import Logging
import OrderedCollections
import SwiftJava
import SwiftJavaConfigurationShared
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
var log: Logger {
translator.log
}
/// 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: SwiftJavaParameterizedType?
/// The Swift names of the interfaces that this class implements.
let swiftInterfaces: [String]
/// Substitution map for resolving generic types.
let substitution: SubstitutionMap
/// The annotations of the Java class.
/// In other words, RUNTIME retained annotations, visible through reflection.
let annotations: [Annotation]
/// Annotations parsed from the .class file's RuntimeInvisibleAnnotations attribute.
/// These are CLASS retained annotations, not visible through reflection.
let runtimeInvisibleAnnotations: JavaRuntimeInvisibleAnnotations
/// 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 {
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 genericParameters: [String] {
if javaTypeParameters.isEmpty {
return []
}
let genericParameters = javaTypeParameters.map { param in
"\(param.getName()): AnyJavaObject"
}
return genericParameters
}
/// 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] ?? []
// Generic substitution.
self.substitution = SubstitutionMap(startingFrom: javaClass)
// Superclass, incl parameter types (if any)
if !javaClass.isInterface() {
var javaSuperclass = javaClass.getSuperclass()
var javaGenericSuperclass: Type? = javaClass.getGenericSuperclass()
var swiftSuperclassName: String? = nil
var swiftSuperclassTypeArgs: [String] = []
while let javaSuperclassNonOpt = javaSuperclass {
do {
swiftSuperclassName = try translator.getSwiftTypeName(javaSuperclassNonOpt, preferValueTypes: false).swiftName
if let javaGenericSuperclass = javaGenericSuperclass?.as(ParameterizedType.self) {
for typeArg in javaGenericSuperclass.getActualTypeArguments() {
let mappedSwiftName = try translator.getSwiftTypeNameAsString(
typeArg!,
substitution: substitution,
preferValueTypes: false,
outerOptional: .nonoptional
)
swiftSuperclassTypeArgs.append(mappedSwiftName)
}
}
break
} catch {
translator.logUntranslated("Unable to translate '\(fullName)' superclass: \(error)")
}
javaSuperclass = javaSuperclassNonOpt.getSuperclass()
javaGenericSuperclass = javaSuperclassNonOpt.getGenericSuperclass()
}
self.effectiveJavaSuperclass = javaSuperclass
self.swiftSuperclass = SwiftJavaParameterizedType(
name: swiftSuperclassName,
typeArguments: swiftSuperclassTypeArgs
)
} else {
self.effectiveJavaSuperclass = nil
self.swiftSuperclass = nil
}
// Interfaces.
self.swiftInterfaces = javaClass.getGenericInterfaces().compactMap { (javaType) -> String? in
guard let javaType else {
return nil
}
do {
return try translator.getSwiftTypeNameAsString(
javaType,
substitution: nil,
preferValueTypes: false,
outerOptional: .nonoptional,
eraseTypeArguments: true
)
} catch {
translator.logUntranslated("Unable to translate '\(fullName)' interface '\(javaType.getTypeName())': \(error)")
return nil
}
}
self.annotations = javaClass.getAnnotations().compactMap(\.self)
// Parse RuntimeInvisibleAnnotations (CLASS-retention) from .class bytes.
let resourcePath = fullName.replacing(".", with: "/") + ".class" // must not have leading `/`
if let inputStream = javaClass.getClassLoader()?.getResourceAsStream(resourcePath) {
do {
let bytes = try inputStream.readAllBytes()
self.runtimeInvisibleAnnotations = JavaClassFileReader.parseRuntimeInvisibleAnnotations(
bytes.map { UInt8(bitPattern: $0) }
)
let classCount = self.runtimeInvisibleAnnotations.classAnnotations.count
let methodCount = self.runtimeInvisibleAnnotations.methodAnnotations.count
let fieldCount = self.runtimeInvisibleAnnotations.fieldAnnotations.count
translator.log.debug("Parsed runtime invisible annotations for '\(fullName)': \(classCount) class, \(methodCount) method, \(fieldCount) field")
} catch {
translator.log.warning("Failed to read .class bytes for '\(fullName)': \(error)")
self.runtimeInvisibleAnnotations = JavaRuntimeInvisibleAnnotations()
}
} else {
translator.log.warning("Could not get resource stream for '\(resourcePath)'")
self.runtimeInvisibleAnnotations = JavaRuntimeInvisibleAnnotations()
}
// 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 }
guard shouldExtract(method: method, config: translator.config) 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
}
guard method.getName().isValidSwiftFunctionName else {
log.warning("Skipping method \(method.getName()) because it is not a valid Swift function name")
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 {
/// Determines whether a method should be extracted for translation.
/// Only look at public and protected methods here.
private func shouldExtract(method: Method, config: Configuration) -> Bool {
// Check exclude filters, if they're applicable to methods:
for exclude in config.filterExclude ?? [] where exclude.contains("#") {
let split = exclude.split(separator: "#")
guard split.count == 2 else {
self.log.warning("Malformed method exclude filter, must have only one '#' marker: \(exclude)")
continue // cannot use this filter, malformed
}
let javaClassName = method.getDeclaringClass().getName()
let javaMemberName = method.getName()
let className = split.first!
let excludedName = split.dropFirst().first!
self.log.warning("Exclude filter: \(exclude) ||| \(javaClassName) / \(javaMemberName)")
if javaClassName.starts(with: className) {
if excludedName.hasSuffix("*"), javaMemberName.starts(with: excludedName.dropLast()) {
log.info("Skip Java member '\(javaClassName)#\(javaMemberName)', prefix exclude matched: \(exclude)")
return false
} else if javaMemberName == excludedName {
log.info("Skip Java member '\(javaClassName)#\(javaMemberName)', exact exclude matched: \(exclude)")
return false
}
}
}
switch self.translator.config.effectiveMinimumInputAccessLevelMode {
case .internal:
return method.isPublic || method.isProtected || method.isPackage
case .package:
return method.isPublic || method.isProtected || method.isPackage
case .public:
return method.isPublic || method.isProtected
}
}
/// Add a field to the appropriate lists(s) for later translation.
private mutating func addField(_ field: Field) {
// Don't include inherited fields when translating to a class.
// This applies to both instance and static fields to avoid duplicates
if translateAsClass && !field.getDeclaringClass()!.equals(javaClass.as(JavaObject.self)!) {
return
}
// Static fields go into a separate list.
if field.isStatic {
// Deduplicate by name: getFields() can return the same field from both an
// interface and its super-interface (e.g. serialVersionUID on Key and PublicKey).
guard !staticFields.contains(where: { $0.getName() == field.getName() }) else {
return
}
staticFields.append(field)
// Enum constants will be used to produce a Swift enum projecting the
// Java enum.
if field.isEnumConstant() {
enumConstants.append(field)
}
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)
} 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 extendsClause: String
let inheritanceClause: String
if translateAsClass {
extendsClause = ""
inheritanceClause =
if let swiftSuperclass, swiftSuperclass.typeArguments.isEmpty {
": \(swiftSuperclass.name)"
} else if let swiftSuperclass {
": \(swiftSuperclass.name)<\(swiftSuperclass.typeArguments.joined(separator: ", "))>"
} else {
""
}
} else {
extendsClause =
if let swiftSuperclass {
", extends: \(swiftSuperclass.render()).self"
} else {
""
}
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: ", "))"
}
let genericParameterClause =
if genericParameters.isEmpty {
""
} else {
"<\(genericParameters.joined(separator: ", "))>"
}
// Emit the struct declaration describing the java class.
let classOrInterface: String = isInterface ? "JavaInterface" : "JavaClass"
let introducer = translateAsClass ? "open class" : "public struct"
let classAvailableAttributes = swiftAvailableAttributes(
from: annotations,
runtimeInvisibleAnnotations: self.runtimeInvisibleAnnotations.classAnnotations,
javaClass: javaClass
)
var classDecl: DeclSyntax =
"""
\(raw: classAvailableAttributes.render())@\(raw: classOrInterface)(\(literal: javaClass.getName())\(raw: extendsClause)\(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] {
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)" // FIXME: move the 'where ...' part into the render bit
} 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,
genericParameters: genericParameters,
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 genericParameters.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)
}
/// A single Swift attribute derived from a Java annotation.
struct SwiftAttribute {
/// The attribute text, e.g. `@available(*, deprecated)`.
var value: String
/// The minimum Swift compiler version required to compile this attribute.
/// When non-nil the attribute is wrapped in a `#if compiler(>=…)` block during rendering.
var minimumCompilerVersion: SwiftVersion? = nil
}
struct SwiftAvailableAttributes {
var attributes: [SwiftAttribute] = []
func render() -> String {
if attributes.isEmpty {
return ""
}
var lines: [String] = []
for attr in attributes {
if let version = attr.minimumCompilerVersion {
let versionString =
version.patch.map { "\(version.major).\(version.minor).\($0)" }
?? "\(version.major).\(version.minor)"
lines.append("#if compiler(>=\(versionString))")
lines.append(attr.value)
lines.append("#endif")
} else {
lines.append(attr.value)
}
}
return lines.joined(separator: "\n") + "\n"
}
}
private func apiLevelComment(_ level: Int32) -> String {
AndroidAPILevel(rawValue: Int(level)).map { " /* \($0.name) */" } ?? ""
}
private func availabilityFromBinRequiresApi(_ binAnnotation: JavaRuntimeInvisibleAnnotation) -> SwiftAttribute? {
let apiLevel: Int32? =
if let api = binAnnotation.elements["api"], api > 0 {
api
} else if let value = binAnnotation.elements["value"], value > 0 {
value
} else {
nil
}
guard let apiLevel else { return nil }
return SwiftAttribute(
value: "@available(Android \(apiLevel)\(apiLevelComment(apiLevel)), *)",
minimumCompilerVersion: .androidPlatformAvailability
)
}
/// Build Swift `@available` attributes from Java annotations on a reflective element.
private func swiftAvailableAttributes(
from runtimeAnnotations: [Annotation],
runtimeInvisibleAnnotations: [JavaRuntimeInvisibleAnnotation] = [],
javaClass: JavaClass<JavaObject>? = nil,
javaMethod: Method? = nil,
javaConstructor: Executable? = nil,
javaFieldName: String? = nil
) -> SwiftAvailableAttributes {
var result = SwiftAvailableAttributes()
for annotation in runtimeAnnotations {
guard let annotationClass = annotation.annotationType() else { continue }
if annotationClass.isKnown(.javaLangDeprecated) {
result.attributes += [SwiftAttribute(value: "@available(*, deprecated)")]
}
}
// Look for any annotations stored in classfiles, e.g. the Android @
for binAnnotation in runtimeInvisibleAnnotations {
let fqn = binAnnotation.fullyQualifiedName
// Handle Android's RequiresApi; though they don't exist in android.jar (!)
if fqn == KnownJavaAnnotation.androidxRequiresApi.rawValue
|| fqn == KnownJavaAnnotation.androidSupportRequiresApi.rawValue
{
if let attr = availabilityFromBinRequiresApi(binAnnotation) {
result.attributes += [attr]
}
}
}
// For android, the RequiresApi actually are synthetic and stored in api-versions.xml,
// so consult that if available
if let apiVersions = translator.androidAPIVersions, let javaClass {
let className = javaClass.getName()
let versionInfo: AndroidAPIAvailability? =
if let javaMethod {
apiVersions.versionInfo(forClass: className, methodDescriptor: jvmMethodDescriptor(javaMethod))
} else if let javaConstructor {
apiVersions.versionInfo(forClass: className, methodDescriptor: jvmMethodDescriptor(javaConstructor))
} else if let fieldName = javaFieldName {
apiVersions.versionInfo(forClass: className, fieldName: fieldName)
} else {
apiVersions.versionInfo(forClass: className)
}
if let info = versionInfo {
let alreadyHasAndroidAvailable = result.attributes.contains {
$0.value.contains("@available(Android")
}
// Only add since from api-versions.xml if @RequiresApi didn't already provide one.
if !alreadyHasAndroidAvailable, let since = info.since, since.rawValue > 0 {
result.attributes += [
SwiftAttribute(
value: "@available(Android \(since.rawValue) /* \(since.name) */, *)",
minimumCompilerVersion: .androidPlatformAvailability
)
]
}
let alreadyHasDeprecated = result.attributes.contains {
$0.value.contains("deprecated")
}
// Handle deprecated APIs; also emit deprecated for removed APIs if not already deprecated.
if !alreadyHasDeprecated, let deprecated = info.deprecated {
result.attributes += [
SwiftAttribute(
value: "@available(Android, deprecated: \(deprecated.rawValue), message: \"Deprecated in Android API \(deprecated.rawValue) /* \(deprecated.name) */\")",
minimumCompilerVersion: .androidPlatformAvailability
)
]
} else if !alreadyHasDeprecated, let removed = info.removed {
// Swift's '@available(Android, unavailable, ...' does not accept a version so we don't use it,
// since it may prevent calling an API that's actually still there in some Android version we're targeting.
result.attributes += [
SwiftAttribute(
value: "@available(Android, deprecated: \(removed.rawValue), message: \"Removed in Android API \(removed.rawValue) /* \(removed.name) */\")",
minimumCompilerVersion: .androidPlatformAvailability
)
]
}
}
}
return result
}
func renderAnnotationExtensions() -> [DeclSyntax] {
var extensions: [DeclSyntax] = []
for annotation in annotations {
guard let annotationClass = annotation.annotationType() else { continue }
if annotationClass.isKnown(.threadSafe) || annotationClass.isKnown(.immutable) {
extensions.append(
"""
extension \(raw: swiftTypeName): @unchecked Swift.Sendable { }
"""
)
} else if annotationClass.isKnown(.notThreadSafe) {
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 {
let parameters: [FunctionParameterSyntax]
parameters = try translateJavaParameters(javaConstructor.getParameters()) + ["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 " : ""
let constructorAnnotations = javaConstructor.getDeclaredAnnotations().compactMap(\.self)
let invisibleCtorAnnotations = runtimeInvisibleAnnotations.annotationsFor(constructor: javaConstructor)
let availableAttributes = swiftAvailableAttributes(
from: constructorAnnotations,
runtimeInvisibleAnnotations: invisibleCtorAnnotations,
javaClass: javaClass,
javaConstructor: javaConstructor
)
// FIXME: handle generics in constructors
return """
\(raw: availableAttributes.render())@JavaMethod
\(raw: nonoverrideAttribute)\(raw: accessModifier)\(raw: convenienceModifier)init(\(raw: parametersStr))\(raw: throwsStr)
"""
}
func genericParameterIsUsedInSignature(_ typeParam: TypeVariable<Method>, in method: Method) -> Bool {
// --- Return type
// Is the return type exactly the type param
// FIXME: make this equals based?
if method.getGenericReturnType().getTypeName() == typeParam.getTypeName() {
return true
}
if let parameterizedReturnType = method.getGenericReturnType().as(ParameterizedType.self) {
for actualTypeParam in parameterizedReturnType.getActualTypeArguments() {
guard let actualTypeParam else { continue }
if actualTypeParam.isEqualTo(typeParam.as(Type.self)) {
return true
}
}
}
if let genericArrayType = method.getGenericReturnType().as(GenericArrayType.self) {
if genericArrayType.getGenericComponentType().isEqualTo(typeParam.as(Type.self)) {
return true
}
}
// --- Parameter types
for parameter in method.getParameters() {
if let parameterizedType = parameter?.getParameterizedType() {
if parameterizedType.isEqualTo(typeParam.as(Type.self)) {
return true
}
// Also check if the type param is used as a type argument inside a parameterized parameter type
if let parameterizedParamType = parameterizedType.as(ParameterizedType.self) {
for actualTypeParam in parameterizedParamType.getActualTypeArguments() {
guard let actualTypeParam else { continue }
if actualTypeParam.isEqualTo(typeParam.as(Type.self)) {
return true
}
}
}
if let genericArrayType = parameterizedType.as(GenericArrayType.self) {
if genericArrayType.getGenericComponentType().isEqualTo(typeParam.as(Type.self)) {
return true
}
}
}
}
return false
}
// TODO: make it more precise with the "origin" of the generic parameter (outer class etc)
func collectMethodGenericParameters(
genericParameters: [String],
method: Method
) -> OrderedSet<String> {
var allGenericParameters = OrderedSet(genericParameters)
let typeParameters = method.getTypeParameters() as [TypeVariable<JavaLangReflect.Method>?]
for typeParameter in typeParameters {
guard let typeParameter else { continue }
guard genericParameterIsUsedInSignature(typeParameter, in: method) else {
continue
}
allGenericParameters.append("\(typeParameter.getTypeName()): AnyJavaObject")
}
return allGenericParameters
}
/// Translates the given Java method into a Swift declaration.
package func renderMethod(
_ javaMethod: Method,
implementedInSwift: Bool,
genericParameters: [String] = [],
whereClause: String = ""
) throws -> DeclSyntax {
// Map the generic params on the method.
let allGenericParameters = collectMethodGenericParameters(genericParameters: genericParameters, method: javaMethod)
let genericParameterClauseStr =
if allGenericParameters.isEmpty {
""
} else {
"<\(allGenericParameters.joined(separator: ", "))>"
}
// Map the parameters.
let parameters = try translateJavaParameters(javaMethod)
let parametersStr = parameters.map { $0.description }.joined(separator: ", ")
// Map the result type.
let resultTypeStr: String
let resultType = try translator.getSwiftReturnTypeNameAsString(
method: javaMethod,
substitution: substitution,
preferValueTypes: true,
outerOptional: .implicitlyUnwrappedOptional
)
let hasTypeEraseGenericResultType: Bool =
isTypeErased(javaMethod.getGenericReturnType())
// FIXME: cleanup the checking here
if resultType != "Void" && resultType != "Swift.Void" {
resultTypeStr = " -> \(resultType)"
} else {
resultTypeStr = ""
}
// --- Handle other effects
let throwsStr = javaMethod.throwsCheckedException ? "throws" : ""
let swiftMethodName = javaMethod.getName().escapedSwiftName
let swiftOptionalMethodName = "\(javaMethod.getName())Optional".escapedSwiftName
// --- Handle docs for the generated method.
// Include the original Java signature
let docsString =
"""
/// Java method `\(javaMethod.getName())`.
///
/// ### Java method signature
/// ```java
/// \(javaMethod.toGenericString())
/// ```
"""
// --- Handle @available attributes from Java annotations (e.g. @Deprecated, @RequiresApi)
let methodAnnotations = javaMethod.getDeclaredAnnotations().compactMap(\.self)
let invisibleMethodAnnotations = runtimeInvisibleAnnotations.annotationsFor(method: javaMethod)
let availableAttributes = swiftAvailableAttributes(
from: methodAnnotations,
runtimeInvisibleAnnotations: invisibleMethodAnnotations,
javaClass: javaClass,
javaMethod: javaMethod
)
// Compute the parameters for '@...JavaMethod(...)'
let methodAttribute: AttributeSyntax
if implementedInSwift {
methodAttribute = ""
} else {
var methodAttributeStr =
if javaMethod.isStatic {
"@JavaStaticMethod"
} else {
"@JavaMethod"
}
// Do we need to record any generic information, in order to enable type-erasure for the upcalls?
var parameters: [String] = []
// If the method name is "init", we need to explicitly specify it in the annotation
// because "init" is a Swift keyword and will be escaped in the function name via `init`
if javaMethod.getName() == "init" {
parameters.append("\"init\"")
}
if hasTypeEraseGenericResultType {
parameters.append("typeErasedResult: \"\(resultType)\"")
}
// TODO: generic parameters?
if !parameters.isEmpty {
methodAttributeStr += "("
methodAttributeStr.append(parameters.joined(separator: ", "))
methodAttributeStr += ")"
}
methodAttributeStr += "\n"