Skip to content

Commit c235a0f

Browse files
madsodgaardktoso
andauthored
Add as to cast wrapped protocols to a concrete type (#819)
Co-authored-by: Konrad `ktoso` Malawski <konrad.malawski@project13.pl>
1 parent a9d0630 commit c235a0f

7 files changed

Lines changed: 261 additions & 4 deletions

File tree

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2026 Apple Inc. and the Swift.org project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of Swift.org project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
package com.example.swift;
16+
17+
import org.junit.jupiter.api.Test;
18+
import org.swift.swiftkit.core.JNISwiftInstance;
19+
import org.swift.swiftkit.core.SwiftArena;
20+
21+
import java.util.Optional;
22+
23+
import static org.junit.jupiter.api.Assertions.*;
24+
25+
/**
26+
* Exercises the dynamic {@code as} downcast (Swift's {@code as?}) that recovers a
27+
* concrete jextracted Swift type from a value returned as {@code any P} / {@code some P}.
28+
*/
29+
public class ReturnProtocolCastTest {
30+
31+
/** Downcast a returned {@code any Greeter} to its concrete Swift struct type. */
32+
@Test
33+
void downcastToConcreteType_succeeds() {
34+
try (var arena = SwiftArena.ofConfined()) {
35+
Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena);
36+
37+
Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena);
38+
assertTrue(english.isPresent());
39+
// `name` is a member of the concrete struct, not visible through the protocol.
40+
assertEquals("World", english.get().getName());
41+
assertEquals("Hello, World!", english.get().greeting());
42+
}
43+
}
44+
45+
/** Downcasting to the wrong dynamic type returns empty (a faithful Swift {@code as?}). */
46+
@Test
47+
void downcastToWrongType_isEmpty() {
48+
try (var arena = SwiftArena.ofConfined()) {
49+
Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena);
50+
51+
Optional<DanishGreeter> danish = greeter.as(DanishGreeter.class, arena);
52+
assertTrue(danish.isEmpty());
53+
}
54+
}
55+
56+
/** {@code some Greeter} (opaque return) downcasts the same as {@code any Greeter}. */
57+
@Test
58+
void downcastOpaqueReturn_succeeds() {
59+
try (var arena = SwiftArena.ofConfined()) {
60+
Greeter greeter = MySwiftLibrary.makeOpaqueGreeter("World", arena);
61+
62+
Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena);
63+
assertTrue(english.isPresent());
64+
assertEquals("World", english.get().getName());
65+
}
66+
}
67+
68+
/**
69+
* {@code as} works on a concrete-typed reference too (the {@code public} variant on
70+
* the class, not the {@code default} on the protocol interface).
71+
*/
72+
@Test
73+
void downcastFromConcreteReference() {
74+
try (var arena = SwiftArena.ofConfined()) {
75+
EnglishGreeter greeter = EnglishGreeter.init("World", arena);
76+
77+
Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena);
78+
assertTrue(english.isPresent());
79+
assertEquals("World", english.get().getName());
80+
81+
Optional<DanishGreeter> danish = greeter.as(DanishGreeter.class, arena);
82+
assertTrue(danish.isEmpty());
83+
}
84+
}
85+
86+
/**
87+
* A Java-implemented conformer has no backing Swift value, so {@code as} returns
88+
* empty rather than crashing (the {@code instanceof JNISwiftInstance} guard). This is
89+
* the case that only exists with Java callbacks enabled.
90+
*/
91+
@Test
92+
void downcastJavaImplementedConformer_isEmpty() {
93+
try (var arena = SwiftArena.ofConfined()) {
94+
Greeter javaGreeter = new Greeter() {
95+
@Override
96+
public String greeting() {
97+
return "Hi from Java";
98+
}
99+
100+
@Override
101+
public String repeated(long count) {
102+
return "Hi from Java";
103+
}
104+
};
105+
assertFalse(javaGreeter instanceof JNISwiftInstance);
106+
107+
Optional<EnglishGreeter> english = javaGreeter.as(EnglishGreeter.class, arena);
108+
assertTrue(english.isEmpty());
109+
}
110+
}
111+
112+
@Test
113+
void downcastResultIsAWorkingInstance() {
114+
try (var arena = SwiftArena.ofConfined()) {
115+
Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena);
116+
117+
EnglishGreeter english = greeter.as(EnglishGreeter.class, arena).orElseThrow();
118+
assertEquals("Hello, World! Hello, World!", english.repeated(2));
119+
}
120+
}
121+
}

‎Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,8 @@ extension JNISwift2JavaGenerator {
197197
if !self.interfaceProtocolWrappers.keys.contains(decl) && !extends.contains("JNISwiftInstance") {
198198
extends.append("JNISwiftInstance")
199199
}
200+
201+
extends.append("SwiftDowncastable")
200202
let extendsString = extends.isEmpty ? "" : " extends \(extends.joined(separator: .comma))"
201203

202204
printer.printBraceBlock("public interface \(decl.effectiveJavaSimpleName)\(extendsString)") { printer in

‎Sources/SwiftJava/SwiftObjects.swift‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,36 @@ extension SwiftObjects {
158158
}
159159
return perform(as: typeMetadata)
160160
}
161+
162+
@JavaMethod
163+
public static func dynamicCast(
164+
environment: UnsafeMutablePointer<JNIEnv?>!,
165+
selfPointer: Int64,
166+
selfTypePointer: Int64,
167+
targetTypePointter: Int64
168+
) -> Int64 {
169+
guard let selfType$ = UnsafeRawPointer(bitPattern: Int(selfTypePointer)) else {
170+
fatalError("selfType metadata address was null")
171+
}
172+
guard let targetType$ = UnsafeRawPointer(bitPattern: Int(targetTypePointter)) else {
173+
fatalError("targetType metadata address was null")
174+
}
175+
176+
let selfTypeMetadata = unsafeBitCast(selfType$, to: Any.Type.self)
177+
let targetTypeMetadata = unsafeBitCast(targetType$, to: Any.Type.self)
178+
179+
func perform<S, T>(srcType: S.Type, targetType: T.Type) -> Int64 {
180+
guard let self$ = UnsafeMutablePointer<S>(bitPattern: Int(selfPointer)) else {
181+
fatalError("self memory address was null")
182+
}
183+
184+
guard let castedValue = self$.pointee as? T else { return 0 }
185+
let castedPointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
186+
castedPointer.initialize(to: castedValue)
187+
return Int64(Int(bitPattern: castedPointer))
188+
}
189+
return perform(srcType: selfTypeMetadata, targetType: targetTypeMetadata)
190+
}
161191
}
162192

163193
public class HashableClass: Hashable {

‎Sources/SwiftJavaDocumentation/Documentation.docc/SupportedFeatures.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ SwiftJava's `swift-java jextract` tool automates generating Java bindings from S
7676
| Existential parameters `f(x: any (A & B)) ` | ❌ | ✅ |
7777
| Existential return types of a single protocol: `f() -> any SomeProtocol` | ❌ | ✅ |
7878
| Existential return types of a composite: `f() -> any (A & B)` | ❌ | ❌ |
79+
| Downcasting a returned protocol value to its concrete type: `greeter.as(EnglishGreeter.class, arena)` | ❌ | ✅ |
7980
| Foundation Data and DataProtocol: `f(x: any DataProtocol) -> Data` | ✅ | ✅ |
8081
| Foundation Date: `f(date: Date) -> Date` | ❌ | ✅ |
8182
| Foundation UUID: `f(uuid: UUID) -> UUID` | ❌ | ✅ |
@@ -395,6 +396,43 @@ Static requirements (`static func`, `init`) and returning a *composite* existent
395396
(`any (A & B)`) are not currently supported; such requirements are simply omitted from
396397
the generated box, and composite returns are not extracted.
397398

399+
#### Downcasting to the concrete type (`as`)
400+
401+
> Note: Downcasting returned protocol values is currently only supported in JNI mode.
402+
403+
A value returned as `any P` / `some P` preserves its concrete dynamic type, so it can be
404+
recovered; This is equivalent to Swift's `as?`, of a checked `instanceof` cast in Java. Every imported protocol `interface` therefore
405+
exposes an `as` method:
406+
407+
```java
408+
<T extends JNISwiftInstance> Optional<T> as(Class<T> type, SwiftArena arena);
409+
<T extends JNISwiftInstance> Optional<T> as(Class<T> type); // uses the default arena
410+
```
411+
412+
`type` must be a concrete jextracted type.
413+
The cast succeeds only when the
414+
value's dynamic Swift type is exactly that type, in which case you receive a fresh binding
415+
registered in the given arena; otherwise the result is `Optional.empty()`.
416+
417+
Continuing the `Greeter` example, where `makeEnglishGreeter` returns `any Greeter` backed
418+
by a concrete `EnglishGreeter`:
419+
420+
```java
421+
try (var arena = SwiftArena.ofConfined()) {
422+
Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena);
423+
424+
Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena);
425+
assertEquals("World", english.orElseThrow().getName());
426+
427+
// A cast to the wrong dynamic type yields an empty Optional:
428+
assertTrue(greeter.as(DanishGreeter.class, arena).isEmpty());
429+
}
430+
```
431+
432+
The cast returns an empty optional if the cast fails, which might happen when
433+
the dynamic type differs, when `type` is not a concrete jextracted type (e.g. a generic type
434+
or another protocol).
435+
398436
### Swift closures
399437

400438
Non-escaping closures are called synchronously by the Swift function they are passed to,
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2026 Apple Inc. and the Swift.org project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of Swift.org project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
package org.swift.swiftkit.core;
16+
17+
import java.lang.reflect.Method;
18+
import java.util.Optional;
19+
20+
/**
21+
* Exposes Swift's dynamic {@code as?} cast on jextracted values: recover a concrete
22+
* jextracted Swift type from a value whose static Java type is a protocol interface
23+
* (e.g. a value returned as {@code any P} / {@code some P}) or any other super-type.
24+
*/
25+
public interface SwiftDowncastable {
26+
27+
/**
28+
* Swift {@code as?}: attempt type-cast this instance to {@code T},
29+
* which must be a non-generic concrete jextracted Swift wrapper type.
30+
*
31+
* @return the type-casted instance, or {@link Optional#empty()} if this value's
32+
* dynamic type is not {@code T}, if this value is not backed by a Swift value
33+
* (e.g. a Java-implemented conformer), or if {@code T} is not a concrete
34+
* jextracted type.
35+
*/
36+
default <T extends JNISwiftInstance> Optional<T> as(Class<T> type, SwiftArena arena) {
37+
if (!(this instanceof JNISwiftInstance)) return Optional.empty();
38+
JNISwiftInstance src = (JNISwiftInstance) this;
39+
try {
40+
// Java does not support static protocol requirements
41+
// and we need to access the type memory address of T
42+
// so we use Java reflection to call the static native downcall instead.
43+
// and also the "constructor" to get back the correct Java wrapper.
44+
Method metadata = type.getDeclaredMethod("$typeMetadataAddressDowncall");
45+
metadata.setAccessible(true);
46+
long targetType = (long) metadata.invoke(null);
47+
long p = SwiftObjects.dynamicCast(src.$memoryAddress(), src.$typeMetadataAddress(), targetType);
48+
if (p == 0) return Optional.empty();
49+
Method wrap = type.getMethod("wrapMemoryAddressUnsafe", long.class, SwiftArena.class);
50+
return Optional.of(type.cast(wrap.invoke(null, p, arena)));
51+
} catch (ReflectiveOperationException e) {
52+
// Not a concrete jextracted type
53+
return Optional.empty();
54+
}
55+
}
56+
57+
/**
58+
* Convenience overload using the default automatic arena.
59+
*
60+
* @see #as(Class, SwiftArena)
61+
*/
62+
default <T extends JNISwiftInstance> Optional<T> as(Class<T> type) {
63+
return as(type, SwiftMemoryManagement.DEFAULT_SWIFT_JAVA_AUTO_ARENA);
64+
}
65+
}

‎SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftObjects.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,5 @@ public static void requireNonZero(long number, String name) {
3131
public static native String typeDescription(long selfTypePointer);
3232
public static native boolean equals(long lhsPointer, long lhsTypePointer, long rhsPointer, long rhsTypePointer);
3333
public static native int hashCode(long selfPointer, long selfTypePointer);
34+
public static native long dynamicCast(long selfPointer, long selfTypePointer, long targetTypePointer);
3435
}

‎Tests/JExtractSwiftTests/JNI/JNIProtocolTests.swift‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ struct JNIProtocolTests {
101101
import org.swift.swiftkit.core.util.*;
102102
""",
103103
"""
104-
public interface SomeProtocol {
104+
public interface SomeProtocol extends SwiftDowncastable {
105105
...
106106
public void method();
107107
...
@@ -123,14 +123,14 @@ struct JNIProtocolTests {
123123
detectChunkByInitialLines: 1,
124124
expectedChunks: [
125125
"""
126-
public interface ParentProtocol {
126+
public interface ParentProtocol extends SwiftDowncastable {
127127
...
128128
public void parentMethod();
129129
...
130130
}
131131
""",
132132
"""
133-
public interface ChildProtocol extends ParentProtocol {
133+
public interface ChildProtocol extends ParentProtocol, SwiftDowncastable {
134134
...
135135
public void childMethod();
136136
...
@@ -594,7 +594,7 @@ struct JNIProtocolTests {
594594
detectChunkByInitialLines: 1,
595595
expectedChunks: [
596596
"""
597-
public interface Loader extends JNISwiftInstance {
597+
public interface Loader extends JNISwiftInstance, SwiftDowncastable {
598598
...
599599
public long load();
600600
...

0 commit comments

Comments
 (0)