forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJNIEnumTests.swift
More file actions
377 lines (362 loc) · 12 KB
/
JNIEnumTests.swift
File metadata and controls
377 lines (362 loc) · 12 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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 JExtractSwiftLib
import Testing
@Suite
struct JNIEnumTests {
let source = """
public enum MyEnum {
case first
case second(String)
case third(x: Int64, y: Int32)
}
"""
@Test
func generatesJavaClass() throws {
try assertOutput(
input: source,
.jni,
.java,
expectedChunks: [
"""
// Generated by jextract-swift
// Swift module: SwiftModule
package com.example.swift;
import org.swift.swiftkit.core.*;
import org.swift.swiftkit.core.util.*;
import org.swift.swiftkit.core.collections.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import org.swift.swiftkit.core.annotations.*;
""",
"""
public final class MyEnum implements JNISwiftInstance {
static final java.lang.String LIB_NAME = "SwiftModule";
@SuppressWarnings("unused")
private static final boolean INITIALIZED_LIBS = initializeLibs();
static boolean initializeLibs() {
System.loadLibrary(SwiftLibraries.LIB_NAME_SWIFT_JAVA);
System.loadLibrary(LIB_NAME);
return true;
}
""",
"""
private MyEnum(long selfPointer, SwiftArena swiftArena) {
SwiftObjects.requireNonZero(selfPointer, "selfPointer");
this.selfPointer = selfPointer;
// Only register once we have fully initialized the object since this will need the object pointer.
swiftArena.register(this);
}
""",
"""
private final long selfPointer;
""",
"""
public long $memoryAddress() {
return this.selfPointer;
}
""",
"""
public static MyEnum wrapMemoryAddressUnsafe(long selfPointer, SwiftArena swiftArena) {
return new MyEnum(selfPointer, swiftArena);
}
""",
"""
@Override
public Runnable $createDestroyFunction() {
long self$ = this.$memoryAddress();
long selfType$ = this.$typeMetadataAddress();
if (CallTraces.TRACE_DOWNCALLS) {
CallTraces.traceDowncall("MyEnum.$createDestroyFunction",
"this", this,
"self", self$);
}
return new Runnable() {
@Override
public void run() {
if (CallTraces.TRACE_DOWNCALLS) {
CallTraces.traceDowncall("MyEnum.$destroy", "self", self$);
}
SwiftObjects.destroy(self$, selfType$);
}
};
}
""",
]
)
}
@Test
func generatesDiscriminator_java() throws {
try assertOutput(
input: source,
.jni,
.java,
detectChunkByInitialLines: 2,
expectedChunks: [
"""
public enum Discriminator {
FIRST,
SECOND,
THIRD
}
""",
"""
public Discriminator getDiscriminator() {
var raw = SwiftObjects.getRawDiscriminator(this.$memoryAddress(), this.$typeMetadataAddress());
return Discriminator.values()[raw];
}
""",
]
)
}
@Test
func generatesDiscriminator_swift() throws {
try assertOutput(
input: source,
.jni,
.swift,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
extension MyEnum: _RawDiscriminatorRepresentable {
public var _rawDiscriminator: Int32 {
switch self {
case .first: return 0
case .second: return 1
case .third: return 2
}
}
}
"""
]
)
}
@Test
func generatesCases_java() throws {
try assertOutput(
input: source,
.jni,
.java,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
public sealed interface Case {}
""",
"""
public Case getCase() {
Discriminator discriminator = this.getDiscriminator();
switch (discriminator) {
case FIRST: return this.getAsFirst().orElseThrow();
case SECOND: return this.getAsSecond().orElseThrow();
case THIRD: return this.getAsThird().orElseThrow();
}
throw new RuntimeException("Unknown discriminator value " + discriminator);
}
""",
"""
public record First() implements Case {
record _NativeParameters() {}
}
""",
"""
public record Second(java.lang.String arg0) implements Case {
record _NativeParameters(java.lang.String arg0) {}
}
""",
"""
public record Third(long x, int y) implements Case {
record _NativeParameters(long x, int y) {}
}
""",
]
)
}
@Test
func generatesCaseInitializers_java() throws {
try assertOutput(
input: source,
.jni,
.java,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
public static MyEnum first(SwiftArena swiftArena) {
return MyEnum.wrapMemoryAddressUnsafe(MyEnum.$first(), swiftArena);
}
""",
"""
public static MyEnum second(java.lang.String arg0, SwiftArena swiftArena) {
return MyEnum.wrapMemoryAddressUnsafe(MyEnum.$second(arg0), swiftArena);
}
""",
"""
public static MyEnum third(long x, int y, SwiftArena swiftArena) {
return MyEnum.wrapMemoryAddressUnsafe(MyEnum.$third(x, y), swiftArena);
}
""",
]
)
}
@Test
func generatesCaseInitializers_swift() throws {
try assertOutput(
input: source,
.jni,
.swift,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
@_cdecl("Java_com_example_swift_MyEnum__00024first__")
public func Java_com_example_swift_MyEnum__00024first__(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass) -> jlong {
let result$ = UnsafeMutablePointer<MyEnum>.allocate(capacity: 1)
result$.initialize(to: MyEnum.first)
let resultBits$ = Int64(Int(bitPattern: result$))
return resultBits$.getJNILocalRefValue(in: environment)
}
""",
"""
@_cdecl("Java_com_example_swift_MyEnum__00024second__Ljava_lang_String_2")
public func Java_com_example_swift_MyEnum__00024second__Ljava_lang_String_2(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, arg0: jstring?) -> jlong {
let result$ = UnsafeMutablePointer<MyEnum>.allocate(capacity: 1)
result$.initialize(to: MyEnum.second(String(fromJNI: arg0, in: environment)))
let resultBits$ = Int64(Int(bitPattern: result$))
return resultBits$.getJNILocalRefValue(in: environment)
}
""",
"""
@_cdecl("Java_com_example_swift_MyEnum__00024third__JI")
public func Java_com_example_swift_MyEnum__00024third__JI(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, x: jlong, y: jint) -> jlong {
let result$ = UnsafeMutablePointer<MyEnum>.allocate(capacity: 1)
result$.initialize(to: MyEnum.third(x: Int64(fromJNI: x, in: environment), y: Int32(fromJNI: y, in: environment)))
let resultBits$ = Int64(Int(bitPattern: result$))
return resultBits$.getJNILocalRefValue(in: environment)
}
""",
]
)
}
@Test
func generatesGetAsCase_java() throws {
try assertOutput(
input: source,
.jni,
.java,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
public Optional<First> getAsFirst() {
if (getDiscriminator() != Discriminator.FIRST) {
return Optional.empty();
}
return Optional.of(new First());
}
""",
"""
public Optional<Second> getAsSecond() {
if (getDiscriminator() != Discriminator.SECOND) {
return Optional.empty();
}
Second._NativeParameters $nativeParameters = MyEnum.$getAsSecond(this.$memoryAddress());
return Optional.of(new Second($nativeParameters.arg0));
}
""",
"""
public Optional<Third> getAsThird() {
if (getDiscriminator() != Discriminator.THIRD) {
return Optional.empty();
}
Third._NativeParameters $nativeParameters = MyEnum.$getAsThird(this.$memoryAddress());
return Optional.of(new Third($nativeParameters.x, $nativeParameters.y));
}
""",
]
)
}
@Test
func generatesGetAsCase_swift() throws {
try assertOutput(
input: source,
.jni,
.swift,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
enum _JNI_MyEnum {
static let myEnumSecondCache = _JNIMethodIDCache(className: "com/example/swift/MyEnum$Second$_NativeParameters", methods: [.init(name: "<init>", signature: "(Ljava/lang/String;)V")])
static let myEnumThirdCache = _JNIMethodIDCache(className: "com/example/swift/MyEnum$Third$_NativeParameters", methods: [.init(name: "<init>", signature: "(JI)V")])
}
""",
"""
@_cdecl("Java_com_example_swift_MyEnum__00024getAsSecond__J")
public func Java_com_example_swift_MyEnum__00024getAsSecond__J(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, selfPointer: jlong) -> jobject? {
...
guard case .second(let _0) = selfPointer$.pointee else {
fatalError("Expected enum case 'second', but was '\\(selfPointer$.pointee)'!")
}
let cache$ = _JNI_MyEnum.myEnumSecondCache
let class$ = cache$.javaClass
let method$ = _JNIMethodIDCache.Method(name: "<init>", signature: "(Ljava/lang/String;)V")
let constructorID$ = cache$[method$]
let newObjectArgs$: [jvalue] = [jvalue(l: _0.getJNILocalRefValue(in: environment) ?? nil)]
return environment.interface.NewObjectA(environment, class$, constructorID$, newObjectArgs$)
}
""",
"""
@_cdecl("Java_com_example_swift_MyEnum__00024getAsThird__J")
public func Java_com_example_swift_MyEnum__00024getAsThird__J(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, selfPointer: jlong) -> jobject? {
...
guard case .third(let x, let y) = selfPointer$.pointee else {
fatalError("Expected enum case 'third', but was '\\(selfPointer$.pointee)'!")
}
let cache$ = _JNI_MyEnum.myEnumThirdCache
let class$ = cache$.javaClass
let method$ = _JNIMethodIDCache.Method(name: "<init>", signature: "(JI)V")
let constructorID$ = cache$[method$]
let newObjectArgs$: [jvalue] = [jvalue(j: x.getJNILocalRefValue(in: environment)), jvalue(i: y.getJNILocalRefValue(in: environment))]
return environment.interface.NewObjectA(environment, class$, constructorID$, newObjectArgs$)
}
""",
],
notExpectedChunks: [
"public func Java_com_example_swift_MyEnum__00024getAsFirst__J("
]
)
}
@Test
func nonGeneratesGetAsCase_swift() throws {
try assertOutput(
input: """
public enum MyEnum {
case first
case second
}
""",
.jni,
.swift,
detectChunkByInitialLines: 1,
expectedChunks: [],
notExpectedChunks: [
"""
enum _JNI_MyEnum
""",
"""
public func Java_com_example_swift_MyEnum__00024getAsFirst__J("
""",
"""
public func Java_com_example_swift_MyEnum__00024getAsSecond__J(
""",
]
)
}
}