-
Notifications
You must be signed in to change notification settings - Fork 112
Add as to cast wrapped protocols to a concrete type
#819
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
925a43a
add dynamicCast to SwiftObjects
madsodgaard b302c2b
print cast function
madsodgaard c123c8a
move to java type instead
madsodgaard 2932ebe
only apply to protocols
madsodgaard 724082d
docs
madsodgaard 795a8f4
Update Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example…
ktoso e0181a1
Apply suggestions from code review
ktoso File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
121 changes: 121 additions & 0 deletions
121
.../SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/ReturnProtocolCastTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift.org open source project | ||
| // | ||
| // Copyright (c) 2026 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 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| package com.example.swift; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.swift.swiftkit.core.JNISwiftInstance; | ||
| import org.swift.swiftkit.core.SwiftArena; | ||
|
|
||
| import java.util.Optional; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.*; | ||
|
|
||
| /** | ||
| * Exercises the dynamic {@code as} downcast (Swift's {@code as?}) that recovers a | ||
| * concrete jextracted Swift type from a value returned as {@code any P} / {@code some P}. | ||
| */ | ||
| public class ReturnProtocolCastTest { | ||
|
|
||
| /** Downcast a returned {@code any Greeter} to its concrete Swift struct type. */ | ||
| @Test | ||
| void downcastToConcreteType_succeeds() { | ||
| try (var arena = SwiftArena.ofConfined()) { | ||
| Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena); | ||
|
|
||
| Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena); | ||
| assertTrue(english.isPresent()); | ||
| // `name` is a member of the concrete struct, not visible through the protocol. | ||
| assertEquals("World", english.get().getName()); | ||
| assertEquals("Hello, World!", english.get().greeting()); | ||
| } | ||
| } | ||
|
|
||
| /** Downcasting to the wrong dynamic type returns empty (a faithful Swift {@code as?}). */ | ||
| @Test | ||
| void downcastToWrongType_isEmpty() { | ||
| try (var arena = SwiftArena.ofConfined()) { | ||
| Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena); | ||
|
|
||
| Optional<DanishGreeter> danish = greeter.as(DanishGreeter.class, arena); | ||
| assertTrue(danish.isEmpty()); | ||
| } | ||
| } | ||
|
|
||
| /** {@code some Greeter} (opaque return) downcasts the same as {@code any Greeter}. */ | ||
| @Test | ||
| void downcastOpaqueReturn_succeeds() { | ||
| try (var arena = SwiftArena.ofConfined()) { | ||
| Greeter greeter = MySwiftLibrary.makeOpaqueGreeter("World", arena); | ||
|
|
||
| Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena); | ||
| assertTrue(english.isPresent()); | ||
| assertEquals("World", english.get().getName()); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * {@code as} works on a concrete-typed reference too (the {@code public} variant on | ||
| * the class, not the {@code default} on the protocol interface). | ||
| */ | ||
| @Test | ||
| void downcastFromConcreteReference() { | ||
| try (var arena = SwiftArena.ofConfined()) { | ||
| EnglishGreeter greeter = EnglishGreeter.init("World", arena); | ||
|
|
||
| Optional<EnglishGreeter> english = greeter.as(EnglishGreeter.class, arena); | ||
| assertTrue(english.isPresent()); | ||
| assertEquals("World", english.get().getName()); | ||
|
|
||
| Optional<DanishGreeter> danish = greeter.as(DanishGreeter.class, arena); | ||
| assertTrue(danish.isEmpty()); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * A Java-implemented conformer has no backing Swift value, so {@code as} returns | ||
| * empty rather than crashing (the {@code instanceof JNISwiftInstance} guard). This is | ||
| * the case that only exists with Java callbacks enabled. | ||
| */ | ||
| @Test | ||
| void downcastJavaImplementedConformer_isEmpty() { | ||
| try (var arena = SwiftArena.ofConfined()) { | ||
| Greeter javaGreeter = new Greeter() { | ||
| @Override | ||
| public String greeting() { | ||
| return "Hi from Java"; | ||
| } | ||
|
|
||
| @Override | ||
| public String repeated(long count) { | ||
| return "Hi from Java"; | ||
| } | ||
| }; | ||
| assertFalse(javaGreeter instanceof JNISwiftInstance); | ||
|
|
||
| Optional<EnglishGreeter> english = javaGreeter.as(EnglishGreeter.class, arena); | ||
| assertTrue(english.isEmpty()); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void downcastResultIsAWorkingInstance() { | ||
| try (var arena = SwiftArena.ofConfined()) { | ||
| Greeter greeter = MySwiftLibrary.makeEnglishGreeter("World", arena); | ||
|
|
||
| EnglishGreeter english = greeter.as(EnglishGreeter.class, arena).orElseThrow(); | ||
| assertEquals("Hello, World! Hello, World!", english.repeated(2)); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 65 additions & 0 deletions
65
SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftDowncastable.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift.org open source project | ||
| // | ||
| // Copyright (c) 2026 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 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| package org.swift.swiftkit.core; | ||
|
|
||
| import java.lang.reflect.Method; | ||
| import java.util.Optional; | ||
|
|
||
| /** | ||
| * Exposes Swift's dynamic {@code as?} cast on jextracted values: recover a concrete | ||
| * jextracted Swift type from a value whose static Java type is a protocol interface | ||
| * (e.g. a value returned as {@code any P} / {@code some P}) or any other super-type. | ||
| */ | ||
| public interface SwiftDowncastable { | ||
|
|
||
| /** | ||
| * Swift {@code as?}: attempt type-cast this instance to {@code T}, | ||
| * which must be a non-generic concrete jextracted Swift wrapper type. | ||
| * | ||
| * @return the type-casted instance, or {@link Optional#empty()} if this value's | ||
| * dynamic type is not {@code T}, if this value is not backed by a Swift value | ||
| * (e.g. a Java-implemented conformer), or if {@code T} is not a concrete | ||
| * jextracted type. | ||
| */ | ||
| default <T extends JNISwiftInstance> Optional<T> as(Class<T> type, SwiftArena arena) { | ||
| if (!(this instanceof JNISwiftInstance)) return Optional.empty(); | ||
| JNISwiftInstance src = (JNISwiftInstance) this; | ||
| try { | ||
| // Java does not support static protocol requirements | ||
| // and we need to access the type memory address of T | ||
| // so we use Java reflection to call the static native downcall instead. | ||
| // and also the "constructor" to get back the correct Java wrapper. | ||
| Method metadata = type.getDeclaredMethod("$typeMetadataAddressDowncall"); | ||
| metadata.setAccessible(true); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We'll get warnings about this AFAIR on newer JDKs unless I'm misremembering, but that's fine for the time being... Better would be to just make the method |
||
| long targetType = (long) metadata.invoke(null); | ||
| long p = SwiftObjects.dynamicCast(src.$memoryAddress(), src.$typeMetadataAddress(), targetType); | ||
| if (p == 0) return Optional.empty(); | ||
| Method wrap = type.getMethod("wrapMemoryAddressUnsafe", long.class, SwiftArena.class); | ||
| return Optional.of(type.cast(wrap.invoke(null, p, arena))); | ||
| } catch (ReflectiveOperationException e) { | ||
| // Not a concrete jextracted type | ||
| return Optional.empty(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Convenience overload using the default automatic arena. | ||
| * | ||
| * @see #as(Class, SwiftArena) | ||
| */ | ||
| default <T extends JNISwiftInstance> Optional<T> as(Class<T> type) { | ||
| return as(type, SwiftMemoryManagement.DEFAULT_SWIFT_JAVA_AUTO_ARENA); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd prefer to not have signatures copy pasted into docs