-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathFFMSwift2JavaGenerator+JavaTranslation.swift
More file actions
966 lines (852 loc) · 35.3 KB
/
FFMSwift2JavaGenerator+JavaTranslation.swift
File metadata and controls
966 lines (852 loc) · 35.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024-2025 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 JavaTypes
import SwiftJavaConfigurationShared
extension FFMSwift2JavaGenerator {
func translatedDecl(
for decl: ImportedFunc
) -> TranslatedFunctionDecl? {
if let cached = translatedDecls[decl] {
return cached
}
let translated: TranslatedFunctionDecl?
do {
let translation = JavaTranslation(
config: self.config,
knownTypes: SwiftKnownTypes(symbolTable: lookupContext.symbolTable)
)
translated = try translation.translate(decl)
} catch {
self.log.info("Failed to translate: '\(decl.swiftDecl.qualifiedNameForDebug)'; \(error)")
translated = nil
}
translatedDecls[decl] = translated
return translated
}
/// Represent a Swift API parameter translated to Java.
struct TranslatedParameter {
/// Java parameter(s) mapped to the Swift parameter.
///
/// Array because one Swift parameter can be mapped to multiple parameters.
var javaParameters: [JavaParameter]
/// Describes how to convert the Java parameter to the lowered arguments for
/// the foreign function.
var conversion: JavaConversionStep
}
/// Represent a Swift API result translated to Java.
struct TranslatedResult {
/// Java type that represents the Swift result type.
var javaResultType: JavaType
/// Java annotations that should be propagated from the result type onto the method
var annotations: [JavaAnnotation] = []
/// Required indirect return receivers for receiving the result.
///
/// 'JavaParameter.name' is the suffix for the receiver variable names. For example
///
/// var _result_pointer = MemorySegment.allocate(...)
/// var _result_count = MemorySegment.allocate(...)
/// downCall(_result_pointer, _result_count)
/// return constructResult(_result_pointer, _result_count)
///
/// This case, there're two out parameter, named '_pointer' and '_count'.
var outParameters: [JavaParameter]
/// Similar to out parameters, but instead of parameters we "fill in" in native,
/// we create an upcall handle before the downcall and pass it to the downcall.
/// Swift then invokes the upcall in order to populate some data in Java (our callback).
///
/// After the call is made, we may need to further extact the result from the called-back-into
/// Java function class, for example:
///
/// var _result_initialize = new $result_initialize.Function();
/// downCall($result_initialize.toUpcallHandle(_result_initialize, arena))
/// return _result_initialize.result
///
var outCallback: OutCallback?
/// Describes how to construct the Java result from the foreign function return
/// value and/or the out parameters.
var conversion: JavaConversionStep
}
/// Translated Java API representing a Swift API.
///
/// Since this holds the lowered signature, and the original `SwiftFunctionSignature`
/// in it, this contains all the API information (except the name) to generate the
/// cdecl thunk, Java binding, and the Java wrapper function.
struct TranslatedFunctionDecl {
/// Java function name.
let name: String
/// Functional interfaces required for the Java method.
let functionTypes: [TranslatedFunctionType]
/// Function signature.
let translatedSignature: TranslatedFunctionSignature
/// Cdecl lowered signature.
let loweredSignature: LoweredFunctionSignature
/// Annotations to include on the Java function declaration
var annotations: [JavaAnnotation] {
self.translatedSignature.annotations
}
}
/// Function signature for a Java API.
struct TranslatedFunctionSignature {
var selfParameter: TranslatedParameter?
var parameters: [TranslatedParameter]
var result: TranslatedResult
// if the result type implied any annotations,
// propagate them onto the function the result is returned from
var annotations: [JavaAnnotation] {
self.result.annotations
}
}
/// Represent a Swift closure type in the user facing Java API.
///
/// Closures are translated to named functional interfaces in Java.
struct TranslatedFunctionType {
var name: String
var parameters: [TranslatedParameter]
var result: TranslatedResult
var swiftType: SwiftFunctionType
var cdeclType: SwiftFunctionType
/// Whether or not this functional interface with C ABI compatible.
var isCompatibleWithC: Bool {
result.conversion.isPlaceholder && parameters.allSatisfy(\.conversion.isPlaceholder)
}
}
struct JavaTranslation {
let config: Configuration
var knownTypes: SwiftKnownTypes
init(config: Configuration, knownTypes: SwiftKnownTypes) {
self.config = config
self.knownTypes = knownTypes
}
func translate(_ decl: ImportedFunc) throws -> TranslatedFunctionDecl {
let lowering = CdeclLowering(knownTypes: knownTypes)
let loweredSignature = try lowering.lowerFunctionSignature(decl.functionSignature)
// Name.
let baseName = switch decl.apiKind {
case .getter, .subscriptGetter: decl.javaGetterName
case .setter, .subscriptSetter: decl.javaSetterName
case .function, .initializer, .enumCase: decl.name
}
// Add parameter labels to make method names unique (for overloading support)
let suffix: String
switch decl.apiKind {
case .getter, .subscriptGetter, .setter, .subscriptSetter:
suffix = ""
default:
suffix = decl.functionSignature.parameters
.map { "_" + ($0.argumentLabel ?? "_") }
.joined()
}
let javaName = baseName + suffix
let javaName =
switch decl.apiKind {
case .getter, .subscriptGetter: decl.javaGetterName
case .setter, .subscriptSetter: decl.javaSetterName
case .function, .initializer, .enumCase: decl.name
}
// Signature.
let translatedSignature = try translate(loweredFunctionSignature: loweredSignature, methodName: javaName)
// Closures.
var funcTypes: [TranslatedFunctionType] = []
for (idx, param) in decl.functionSignature.parameters.enumerated() {
switch param.type {
case .function(let funcTy):
let paramName = param.parameterName ?? "_\(idx)"
guard case .function(let cdeclTy) = loweredSignature.parameters[idx].cdeclParameters[0].type else {
preconditionFailure("closure parameter wasn't lowered to a function type; \(funcTy)")
}
let translatedClosure = try translateFunctionType(name: paramName, swiftType: funcTy, cdeclType: cdeclTy)
funcTypes.append(translatedClosure)
case .tuple:
// TODO: Implement
break
default:
break
}
}
return TranslatedFunctionDecl(
name: javaName,
functionTypes: funcTypes,
translatedSignature: translatedSignature,
loweredSignature: loweredSignature
)
}
/// Translate Swift closure type to Java functional interface.
func translateFunctionType(
name: String,
swiftType: SwiftFunctionType,
cdeclType: SwiftFunctionType
) throws -> TranslatedFunctionType {
var translatedParams: [TranslatedParameter] = []
for (i, param) in swiftType.parameters.enumerated() {
let paramName = param.parameterName ?? "_\(i)"
translatedParams.append(
try translateClosureParameter(param.type, convention: param.convention, parameterName: paramName)
)
}
guard let resultCType = try? CType(cdeclType: swiftType.resultType) else {
throw JavaTranslationError.unhandledType(.function(swiftType))
}
let transltedResult = TranslatedResult(
javaResultType: resultCType.javaType,
outParameters: [],
conversion: .placeholder
)
return TranslatedFunctionType(
name: name,
parameters: translatedParams,
result: transltedResult,
swiftType: swiftType,
cdeclType: cdeclType
)
}
func translateClosureParameter(
_ type: SwiftType,
convention: SwiftParameterConvention,
parameterName: String
) throws -> TranslatedParameter {
if let cType = try? CType(cdeclType: type) {
return TranslatedParameter(
javaParameters: [
JavaParameter(name: parameterName, type: cType.javaType)
],
conversion: .placeholder
)
}
switch type {
case .nominal(let nominal):
if let knownType = nominal.nominalTypeDecl.knownTypeKind {
switch knownType {
case .unsafeRawBufferPointer, .unsafeMutableRawBufferPointer:
return TranslatedParameter(
javaParameters: [
JavaParameter(name: parameterName, type: .javaForeignMemorySegment)
],
conversion: .method(
.explodedName(component: "pointer"),
methodName: "reinterpret",
arguments: [
.explodedName(component: "count")
],
withArena: false
)
)
default:
break
}
}
default:
break
}
throw JavaTranslationError.unhandledType(type)
}
/// Translate a Swift API signature to the user-facing Java API signature.
///
/// Note that the result signature is for the high-level Java API, not the
/// low-level FFM down-calling interface.
func translate(
loweredFunctionSignature: LoweredFunctionSignature,
methodName: String
) throws -> TranslatedFunctionSignature {
let swiftSignature = loweredFunctionSignature.original
// 'self'
let selfParameter: TranslatedParameter?
if case .instance(let swiftSelf) = swiftSignature.selfParameter {
selfParameter = try self.translateParameter(
type: swiftSelf.type,
convention: swiftSelf.convention,
parameterName: swiftSelf.parameterName ?? "self",
loweredParam: loweredFunctionSignature.selfParameter!,
methodName: methodName,
genericParameters: swiftSignature.genericParameters,
genericRequirements: swiftSignature.genericRequirements
)
} else {
selfParameter = nil
}
// Regular parameters.
let parameters: [TranslatedParameter] = try swiftSignature.parameters.enumerated()
.map { (idx, swiftParam) in
let loweredParam = loweredFunctionSignature.parameters[idx]
let parameterName = swiftParam.parameterName ?? "_\(idx)"
return try self.translateParameter(
type: swiftParam.type,
convention: swiftParam.convention,
parameterName: parameterName,
loweredParam: loweredParam,
methodName: methodName,
genericParameters: swiftSignature.genericParameters,
genericRequirements: swiftSignature.genericRequirements
)
}
// Result.
let result = try self.translateResult(
swiftResult: swiftSignature.result,
loweredResult: loweredFunctionSignature.result
)
return TranslatedFunctionSignature(
selfParameter: selfParameter,
parameters: parameters,
result: result
)
}
/// Translate a Swift API parameter to the user-facing Java API parameter.
func translateParameter(
type swiftType: SwiftType,
convention: SwiftParameterConvention,
parameterName: String,
loweredParam: LoweredParameter,
methodName: String,
genericParameters: [SwiftGenericParameterDeclaration],
genericRequirements: [SwiftGenericRequirement]
) throws -> TranslatedParameter {
// If the result type should cause any annotations on the method, include them here.
let parameterAnnotations: [JavaAnnotation] = getTypeAnnotations(swiftType: swiftType, config: config)
// If there is a 1:1 mapping between this Swift type and a C type, that can
// be expressed as a Java primitive type.
if let cType = try? CType(cdeclType: swiftType) {
let javaType = cType.javaType
return TranslatedParameter(
javaParameters: [
JavaParameter(
name: parameterName,
type: javaType,
annotations: parameterAnnotations
)
],
conversion: .placeholder
)
}
switch swiftType {
case .metatype:
// Metatype are expressed as 'org.swift.swiftkit.SwiftAnyType'
return TranslatedParameter(
javaParameters: [
JavaParameter(
name: parameterName,
type: JavaType.class(package: "org.swift.swiftkit.ffm", name: "SwiftAnyType"),
annotations: parameterAnnotations
)
],
conversion: .swiftValueSelfSegment(.placeholder)
)
case .nominal(let swiftNominalType):
if let knownType = swiftNominalType.nominalTypeDecl.knownTypeKind {
if convention == .inout {
// FIXME: Support non-trivial 'inout' for builtin types.
throw JavaTranslationError.inoutNotSupported(swiftType)
}
switch knownType {
case .unsafePointer, .unsafeMutablePointer:
// FIXME: Implement
throw JavaTranslationError.unhandledType(swiftType)
case .unsafeBufferPointer, .unsafeMutableBufferPointer:
// FIXME: Implement
throw JavaTranslationError.unhandledType(swiftType)
case .unsafeRawBufferPointer, .unsafeMutableRawBufferPointer:
return TranslatedParameter(
javaParameters: [
JavaParameter(name: parameterName, type: .javaForeignMemorySegment)
],
conversion: .commaSeparated([
.placeholder,
.method(.placeholder, methodName: "byteSize", arguments: [], withArena: false),
])
)
case .optional:
guard let genericArgs = swiftNominalType.genericArguments, genericArgs.count == 1 else {
throw JavaTranslationError.unhandledType(swiftType)
}
return try translateOptionalParameter(
wrappedType: genericArgs[0],
convention: convention,
parameterName: parameterName,
loweredParam: loweredParam,
methodName: methodName,
genericParameters: genericParameters,
genericRequirements: genericRequirements
)
case .string:
return TranslatedParameter(
javaParameters: [
JavaParameter(
name: parameterName,
type: .javaLangString
)
],
conversion: .call(.placeholder, function: "SwiftRuntime.toCString", withArena: true)
)
case .foundationData, .essentialsData:
break
default:
throw JavaTranslationError.unhandledType(swiftType)
}
}
// Generic types are not supported yet.
guard swiftNominalType.genericArguments == nil else {
throw JavaTranslationError.unhandledType(swiftType)
}
return TranslatedParameter(
javaParameters: [
JavaParameter(
name: parameterName,
type: try translate(swiftType: swiftType)
)
],
conversion: .swiftValueSelfSegment(.placeholder)
)
case .tuple:
// TODO: Implement.
throw JavaTranslationError.unhandledType(swiftType)
case .function:
return TranslatedParameter(
javaParameters: [
JavaParameter(
name: parameterName,
type: JavaType.class(package: nil, name: "\(methodName).\(parameterName)")
)
],
conversion: .call(.placeholder, function: "\(methodName).$toUpcallStub", withArena: true)
)
case .existential, .opaque, .genericParameter:
if let concreteTy = swiftType.representativeConcreteTypeIn(
knownTypes: knownTypes,
genericParameters: genericParameters,
genericRequirements: genericRequirements
) {
return try translateParameter(
type: concreteTy,
convention: convention,
parameterName: parameterName,
loweredParam: loweredParam,
methodName: methodName,
genericParameters: genericParameters,
genericRequirements: genericRequirements
)
}
// Otherwise, not supported yet.
throw JavaTranslationError.unhandledType(swiftType)
case .optional(let wrapped):
return try translateOptionalParameter(
wrappedType: wrapped,
convention: convention,
parameterName: parameterName,
loweredParam: loweredParam,
methodName: methodName,
genericParameters: genericParameters,
genericRequirements: genericRequirements
)
case .composite:
throw JavaTranslationError.unhandledType(swiftType)
case .array(let wrapped) where wrapped == knownTypes.uint8:
return TranslatedParameter(
javaParameters: [
JavaParameter(name: parameterName, type: .array(.byte), annotations: parameterAnnotations)
],
conversion:
.commaSeparated([
.call(
.commaSeparated([.constant("ValueLayout.JAVA_BYTE"), .placeholder]),
base: .temporaryArena,
function: "allocateFrom",
withArena: false // this would pass the arena as last argument, but instead we make a call on the arena
),
.property(.placeholder, propertyName: "length"),
])
)
case .array:
throw JavaTranslationError.unhandledType(swiftType)
}
}
/// Translate an Optional Swift API parameter to the user-facing Java API parameter.
func translateOptionalParameter(
wrappedType swiftType: SwiftType,
convention: SwiftParameterConvention,
parameterName: String,
loweredParam: LoweredParameter,
methodName: String,
genericParameters: [SwiftGenericParameterDeclaration],
genericRequirements: [SwiftGenericRequirement]
) throws -> TranslatedParameter {
// If there is a 1:1 mapping between this Swift type and a C type, that can
// be expressed as a Java primitive type.
if let cType = try? CType(cdeclType: swiftType) {
let (translatedClass, lowerFunc) =
switch cType.javaType {
case .int: ("OptionalInt", "toOptionalSegmentInt")
case .long: ("OptionalLong", "toOptionalSegmentLong")
case .double: ("OptionalDouble", "toOptionalSegmentDouble")
case .boolean: ("Optional<Boolean>", "toOptionalSegmentBoolean")
case .byte: ("Optional<Byte>", "toOptionalSegmentByte")
case .char: ("Optional<Character>", "toOptionalSegmentCharacter")
case .short: ("Optional<Short>", "toOptionalSegmentShort")
case .float: ("Optional<Float>", "toOptionalSegmentFloat")
default:
throw JavaTranslationError.unhandledType(.optional(swiftType))
}
return TranslatedParameter(
javaParameters: [
JavaParameter(name: parameterName, type: JavaType(className: translatedClass))
],
conversion: .call(.placeholder, function: "SwiftRuntime.\(lowerFunc)", withArena: true)
)
}
switch swiftType {
case .nominal(let nominal):
if let knownType = nominal.nominalTypeDecl.knownTypeKind {
switch knownType {
case .foundationData, .foundationDataProtocol:
break
case .essentialsData, .essentialsDataProtocol:
break
default:
throw JavaTranslationError.unhandledType(.optional(swiftType))
}
}
let translatedTy = try self.translate(swiftType: swiftType)
return TranslatedParameter(
javaParameters: [
JavaParameter(name: parameterName, type: JavaType(className: "Optional<\(translatedTy.description)>"))
],
conversion: .call(.placeholder, function: "SwiftRuntime.toOptionalSegmentInstance", withArena: false)
)
case .existential, .opaque, .genericParameter:
if let concreteTy = swiftType.representativeConcreteTypeIn(
knownTypes: knownTypes,
genericParameters: genericParameters,
genericRequirements: genericRequirements
) {
return try translateOptionalParameter(
wrappedType: concreteTy,
convention: convention,
parameterName: parameterName,
loweredParam: loweredParam,
methodName: methodName,
genericParameters: genericParameters,
genericRequirements: genericRequirements
)
}
throw JavaTranslationError.unhandledType(.optional(swiftType))
case .tuple(let tuple):
if tuple.count == 1 {
return try translateOptionalParameter(
wrappedType: tuple[0],
convention: convention,
parameterName: parameterName,
loweredParam: loweredParam,
methodName: methodName,
genericParameters: genericParameters,
genericRequirements: genericRequirements
)
}
throw JavaTranslationError.unhandledType(.optional(swiftType))
default:
throw JavaTranslationError.unhandledType(.optional(swiftType))
}
}
/// Translate a Swift API result to the user-facing Java API result.
func translateResult(
swiftResult: SwiftResult,
loweredResult: LoweredResult
) throws -> TranslatedResult {
let swiftType = swiftResult.type
// If the result type should cause any annotations on the method, include them here.
let resultAnnotations: [JavaAnnotation] = getTypeAnnotations(swiftType: swiftType, config: config)
// If there is a 1:1 mapping between this Swift type and a C type, that can
// be expressed as a Java primitive type.
if let cType = try? CType(cdeclType: swiftType) {
let javaType = cType.javaType
return TranslatedResult(
javaResultType: javaType,
annotations: resultAnnotations,
outParameters: [],
conversion: .placeholder
)
}
switch swiftType {
case .metatype(_):
// Metatype are expressed as 'org.swift.swiftkit.SwiftAnyType'
let javaType = JavaType.class(package: "org.swift.swiftkit.ffm", name: "SwiftAnyType")
return TranslatedResult(
javaResultType: javaType,
annotations: resultAnnotations,
outParameters: [],
conversion: .construct(.placeholder, javaType)
)
case .nominal(let swiftNominalType):
if let knownType = swiftNominalType.nominalTypeDecl.knownTypeKind {
switch knownType {
case .unsafeRawBufferPointer, .unsafeMutableRawBufferPointer:
return TranslatedResult(
javaResultType: .javaForeignMemorySegment,
annotations: resultAnnotations,
outParameters: [
JavaParameter(name: "pointer", type: .javaForeignMemorySegment),
JavaParameter(name: "count", type: .long),
],
conversion: .method(
.readMemorySegment(.explodedName(component: "pointer"), as: .javaForeignMemorySegment),
methodName: "reinterpret",
arguments: [
.readMemorySegment(.explodedName(component: "count"), as: .long)
],
withArena: false
)
)
case .foundationData, .essentialsData:
break // Implemented as wrapper
case .unsafePointer, .unsafeMutablePointer:
// FIXME: Implement
throw JavaTranslationError.unhandledType(swiftType)
case .unsafeBufferPointer, .unsafeMutableBufferPointer:
// FIXME: Implement
throw JavaTranslationError.unhandledType(swiftType)
case .string:
// FIXME: Implement
throw JavaTranslationError.unhandledType(swiftType)
default:
throw JavaTranslationError.unhandledType(swiftType)
}
}
// Generic types are not supported yet.
guard swiftNominalType.genericArguments == nil else {
throw JavaTranslationError.unhandledType(swiftType)
}
let javaType: JavaType = .class(package: nil, name: swiftNominalType.nominalTypeDecl.name)
return TranslatedResult(
javaResultType: javaType,
annotations: resultAnnotations,
outParameters: [
JavaParameter(name: "", type: javaType)
],
conversion: .wrapMemoryAddressUnsafe(.placeholder, javaType)
)
case .tuple:
// TODO: Implement.
throw JavaTranslationError.unhandledType(swiftType)
case .array(let wrapped) where wrapped == knownTypes.uint8:
return TranslatedResult(
javaResultType:
.array(.byte),
annotations: [.unsigned],
outParameters: [], // no out parameters, but we do an "out" callback
outCallback: OutCallback(
name: "$_result_initialize",
members: [
"byte[] result = null"
],
parameters: [
JavaParameter(name: "pointer", type: .javaForeignMemorySegment),
JavaParameter(name: "count", type: .long),
],
cFunc: CFunction(
resultType: .void,
name: "apply",
parameters: [
CParameter(type: .pointer(.void)),
CParameter(type: .integral(.size_t)),
],
isVariadic: false
),
body:
"this.result = _0.reinterpret(_1).toArray(ValueLayout.JAVA_BYTE); // copy native Swift array to Java heap array"
),
conversion: .initializeResultWithUpcall(
[
.introduceVariable(
name: "_result_initialize",
initializeWith: .javaNew(
.commaSeparated(
[
// We need to refer to the nested class that is created for this function.
// The class that contains all the related functional interfaces is called the same
// as the downcall function, so we use the thunk name to find this class/
.placeholderForSwiftThunkName, .constant("$_result_initialize.Function$Impl()"),
],
separator: "."
)
)
),
// .constant("var = new \(.placeholderForDowncallThunkName).."),
.placeholderForDowncall, // perform the downcall here
],
extractResult: .property(.constant("_result_initialize"), propertyName: "result")
)
)
case .genericParameter, .optional, .function, .existential, .opaque, .composite, .array:
throw JavaTranslationError.unhandledType(swiftType)
}
}
func translate(
swiftType: SwiftType
) throws -> JavaType {
guard let nominalName = swiftType.asNominalTypeDeclaration?.name else {
throw JavaTranslationError.unhandledType(swiftType)
}
return .class(package: nil, name: nominalName)
}
}
/// Describes how to convert values between Java types and FFM types.
enum JavaConversionStep {
/// The input
case placeholder
/// The "downcall", e.g. `swiftjava_SwiftModule_returnArray.call(...)`.
/// This can be used in combination with aggregate conversion steps to prepare a setup and processing of the downcall.
case placeholderForDowncall
/// Placeholder for Swift thunk name, e.g. "swiftjava_SwiftModule_returnArray".
///
/// This is derived from the placeholderForDowncall substitution - could be done more cleanly,
/// however this has the benefit of not needing to pass the name substituion separately.
case placeholderForSwiftThunkName
/// The temporary `arena$` that is necessary to complete the conversion steps.
///
/// This is distinct from just a constant 'arena$' string, since it forces the creation of a temporary arena.
case temporaryArena
/// The input exploded into components.
case explodedName(component: String)
/// A fixed value
case constant(String)
/// The result of the function will be initialized with a callback to Java (an upcall).
///
/// The `extractResult` is used for the actual `return ...` statement, because we need to extract
/// the return value from the called back into class, e.g. `return _result_initialize.result`.
indirect case initializeResultWithUpcall([JavaConversionStep], extractResult: JavaConversionStep)
/// 'value.$memorySegment()'
indirect case swiftValueSelfSegment(JavaConversionStep)
/// Call specified function using the placeholder as arguments.
///
/// The 'base' is if the call should be performed as 'base.function',
/// otherwise the function is assumed to be a free function.
///
/// If `withArena` is true, `arena$` argument is added.
indirect case call(JavaConversionStep, base: JavaConversionStep?, function: String, withArena: Bool)
static func call(_ step: JavaConversionStep, function: String, withArena: Bool) -> Self {
.call(step, base: nil, function: function, withArena: withArena)
}
// TODO: just use make call more powerful and use it instead?
/// Apply a method on the placeholder.
/// If `withArena` is true, `arena$` argument is added.
indirect case method(JavaConversionStep, methodName: String, arguments: [JavaConversionStep] = [], withArena: Bool)
/// Fetch a property from the placeholder.
/// Similar to 'method', however for a property i.e. without adding the '()' after the name
indirect case property(JavaConversionStep, propertyName: String)
/// Call 'new \(Type)(\(placeholder), swiftArena$)'.
indirect case constructSwiftValue(JavaConversionStep, JavaType)
/// Construct the type using the placeholder as arguments.
indirect case construct(JavaConversionStep, JavaType)
/// Call the `MyType.wrapMemoryAddressUnsafe` in order to wrap a memory address using the Java binding type
indirect case wrapMemoryAddressUnsafe(JavaConversionStep, JavaType)
/// Introduce a local variable, e.g. `var result = new Something()`
indirect case introduceVariable(name: String, initializeWith: JavaConversionStep)
/// Casting the placeholder to the certain type.
indirect case cast(JavaConversionStep, JavaType)
/// Prefix the conversion step with a java `new`.
///
/// This is useful if constructing the value is complex and we use
/// a combination of separated values and constants to do so; Generally prefer using `construct`
/// if you only want to construct a "wrapper" for the current `.placeholder`.
indirect case javaNew(JavaConversionStep)
/// Convert the results of the inner steps to a comma separated list.
indirect case commaSeparated([JavaConversionStep], separator: String = ", ")
/// Refer an exploded argument suffixed with `_\(name)`.
indirect case readMemorySegment(JavaConversionStep, as: JavaType)
var isPlaceholder: Bool {
if case .placeholder = self { true } else { false }
}
}
}
extension FFMSwift2JavaGenerator.TranslatedFunctionSignature {
/// Whether or not if the down-calling requires temporary "Arena" which is
/// only used during the down-calling.
var requiresTemporaryArena: Bool {
if self.parameters.contains(where: { $0.conversion.requiresTemporaryArena }) {
return true
}
if self.selfParameter?.conversion.requiresTemporaryArena ?? false {
return true
}
if self.result.conversion.requiresTemporaryArena {
return true
}
return false
}
/// Whether if the down-calling requires "SwiftArena" or not, which should be
/// passed-in by the API caller. This is needed if the API returns a `SwiftValue`
var requiresSwiftArena: Bool {
self.result.conversion.requiresSwiftArena
}
}
extension CType {
/// Map lowered C type to Java type for FFM binding.
var javaType: JavaType {
switch self {
case .void: return .void
case .integral(.bool): return .boolean
case .integral(.signed(bits: 8)): return .byte
case .integral(.signed(bits: 16)): return .short
case .integral(.signed(bits: 32)): return .int
case .integral(.signed(bits: 64)): return .long
case .integral(.unsigned(bits: 8)): return .byte
case .integral(.unsigned(bits: 16)): return .char // char is Java's only unsigned primitive, we can use it!
case .integral(.unsigned(bits: 32)): return .int
case .integral(.unsigned(bits: 64)): return .long
case .floating(.float): return .float
case .floating(.double): return .double
// FIXME: 32 bit consideration.
// The 'FunctionDescriptor' uses 'SWIFT_INT' which relies on the running
// machine arch. That means users can't pass Java 'long' values to the
// function without casting. But how do we generate code that runs both
// 32 and 64 bit machine?
case .integral(.ptrdiff_t), .integral(.size_t):
return .long
case .pointer(_), .function(resultType: _, parameters: _, variadic: _):
return .javaForeignMemorySegment
case .qualified(const: _, volatile: _, let inner):
return inner.javaType
case .tag(_):
fatalError("unsupported")
case .integral(.signed(bits: _)), .integral(.unsigned(bits: _)):
fatalError("unreachable")
}
}
/// Map lowered C type to FFM ValueLayout.
var foreignValueLayout: ForeignValueLayout {
switch self {
case .integral(.bool): return .SwiftBool
case .integral(.signed(bits: 8)): return .SwiftInt8
case .integral(.signed(bits: 16)): return .SwiftInt16
case .integral(.signed(bits: 32)): return .SwiftInt32
case .integral(.signed(bits: 64)): return .SwiftInt64
case .integral(.unsigned(bits: 8)): return .SwiftUInt8
case .integral(.unsigned(bits: 16)): return .SwiftUInt16
case .integral(.unsigned(bits: 32)): return .SwiftUInt32
case .integral(.unsigned(bits: 64)): return .SwiftUInt64
case .floating(.double): return .SwiftDouble
case .floating(.float): return .SwiftFloat
case .integral(.ptrdiff_t), .integral(.size_t):
return .SwiftInt
case .pointer(_), .function(resultType: _, parameters: _, variadic: _):
return .SwiftPointer
case .qualified(const: _, volatile: _, type: let inner):
return inner.foreignValueLayout
case .tag(_):
fatalError("unsupported")
case .void, .integral(.signed(bits: _)), .integral(.unsigned(bits: _)):
fatalError("unreachable")
}
}
}
enum JavaTranslationError: Error {
case inoutNotSupported(SwiftType, file: String = #file, line: Int = #line)
case unhandledType(SwiftType, file: String = #file, line: Int = #line)
}