Skip to content

Commit

Permalink
Support Option<OpaqueSwiftType> (#272)
Browse files Browse the repository at this point in the history
This adds support for bridging `Option<OpaqueSwiftType>` in `extern "Rust"` functions. This fixes #268, and makes the following now possible:

```rs
#[swift_bridge::bridge]
mod ffi {
    extern "Swift" {
        type SomeSwiftType;
    }

    extern "Rust" {
        fn option_arg(arg: Option<SomeSwiftType>);
        fn returns_option() -> Option<SomeSwiftType>;
    }
}
```
  • Loading branch information
Bright-Shard committed Apr 28, 2024
1 parent c3c950c commit 636fa27
Show file tree
Hide file tree
Showing 11 changed files with 392 additions and 176 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ func swift_arg_option_str(arg: Optional<RustStr>) -> Bool {
} else {
return false
}

}

public class OptTestOpaqueSwiftType {
let val: Int

init(val: Int) {
self.val = val
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,34 @@ class OptionTests: XCTestCase {
func testSwiftCallRustOptionPrimitive() throws {
XCTAssertEqual(rust_reflect_option_u8(70), 70)
XCTAssertEqual(rust_reflect_option_u8(nil), nil)

XCTAssertEqual(rust_reflect_option_i8(70), 70)
XCTAssertEqual(rust_reflect_option_i8(nil), nil)

XCTAssertEqual(rust_reflect_option_u16(70), 70)
XCTAssertEqual(rust_reflect_option_u16(nil), nil)

XCTAssertEqual(rust_reflect_option_i16(70), 70)
XCTAssertEqual(rust_reflect_option_i16(nil), nil)

XCTAssertEqual(rust_reflect_option_u32(70), 70)
XCTAssertEqual(rust_reflect_option_u32(nil), nil)

XCTAssertEqual(rust_reflect_option_i32(70), 70)
XCTAssertEqual(rust_reflect_option_i32(nil), nil)

XCTAssertEqual(rust_reflect_option_u64(70), 70)
XCTAssertEqual(rust_reflect_option_u64(nil), nil)

XCTAssertEqual(rust_reflect_option_i64(70), 70)
XCTAssertEqual(rust_reflect_option_i64(nil), nil)

XCTAssertEqual(rust_reflect_option_f32(70.0), 70.0)
XCTAssertEqual(rust_reflect_option_f32(nil), nil)

XCTAssertEqual(rust_reflect_option_f64(70.0), 70.0)
XCTAssertEqual(rust_reflect_option_f64(nil), nil)

XCTAssertEqual(rust_reflect_option_bool(true), true)
XCTAssertEqual(rust_reflect_option_bool(false), false)
XCTAssertEqual(rust_reflect_option_bool(nil), nil)
Expand All @@ -52,30 +52,30 @@ class OptionTests: XCTestCase {
func testRustCallSwiftOptionPrimitive() throws {
test_rust_calls_swift_option_primitive()
}

/// Verify that Swift can call a Rust function that accepts and returns an Option<T>
/// where T is a String.
func testSwiftCallRustReturnOptionString() throws {
let string = rust_reflect_option_string("hello world")
XCTAssertEqual(string!.toString(), "hello world")

let none: String? = nil
XCTAssertNil(rust_reflect_option_string(none))
}

/// We use an `Option<&'static str>` that we create on the Rust side so that
/// we don't run into any lifetime issues.
func testSwiftCallRustReturnOptionStr() throws {
let str = rust_create_option_static_str()
XCTAssertEqual(str!.toString(), "hello")

let reflected = rust_reflect_option_str(str)
XCTAssertEqual(reflected!.toString(), "hello")

let none: RustStr? = nil
XCTAssertNil(rust_reflect_option_str(none))
}

func testSwiftCallRustWithOptionVecOfPrimitiveType() throws {
let vec = RustVec<UInt16>()
vec.push(value: 123)
Expand All @@ -89,15 +89,24 @@ class OptionTests: XCTestCase {

XCTAssertNil(rust_reflect_option_vector_rust_type(nil))
}

func testSwiftCallRustWithOptionOpaqueRustType() throws {
let val = OptTestOpaqueRustType(123)
let reflect = rust_reflect_option_opaque_rust_type(val)
XCTAssertEqual(reflect!.field(), 123)

XCTAssertNil(rust_reflect_option_opaque_rust_type(nil))
}

/// Verify that we can bridge options of opaque Swift types.
func testSwiftCallRustWithOptionOpaqueSwiftType() throws {
let val = OptTestOpaqueSwiftType(val: 727)
let reflect = rust_reflect_option_opaque_swift_type(val)
XCTAssertEqual(reflect!.val, 727)

XCTAssertNil(rust_reflect_option_opaque_swift_type(nil))
}

/// Verify that we can pass and receive an `Option<&RustType>`.
///
/// We deinitialize the first reference and create a second to confirm that
Expand All @@ -110,39 +119,39 @@ class OptionTests: XCTestCase {
XCTAssertEqual(reflect!.field(), 123)
XCTAssertNil(rust_reflect_option_ref_opaque_rust_type(nil))
reflect = nil

reflect = rust_reflect_option_ref_opaque_rust_type(opt_ref)
XCTAssertEqual(reflect!.field(), 123)
}

func testSwiftCallRustWithOptionOpaqueRustCopyType() throws {
let val = new_opaque_rust_copy_type(123)
let _: OptTestOpaqueRustCopyType? = rust_reflect_option_opaque_rust_copy_type(val)

// TODO: Support methods on generic types
// XCTAssertEqual(reflect!.field(), 123)
XCTAssertNil(rust_reflect_option_opaque_rust_copy_type(nil))
}

func testSwiftCallRustWithOptionGenericOpaqueRustType() throws {
let val = new_generic_opaque_rust_type(123)
let _: OptTestGenericOpaqueRustType<UInt8>? = rust_reflect_option_generic_opaque_rust_type(val)

// TODO: Support methods on generic types
// XCTAssertEqual(reflect!.field(), 123)
XCTAssertNil(rust_reflect_option_opaque_rust_type(nil))
}

func testSwiftCallRustWithOptionGenericOpaqueRustCopyType() throws {
let val = new_generic_opaque_rust_copy_type(123)
let _: OptTestGenericOpaqueRustCopyType? = rust_reflect_option_generic_opaque_rust_copy_type(val)

// TODO: Support methods on generic types
// XCTAssertEqual(reflect!.field(), 123)
XCTAssertNil(rust_reflect_option_generic_opaque_rust_copy_type(nil))
}


func testStructWithOptionFieldsSome() throws {
let val = StructWithOptionFields(
u8: 123, i8: 123, u16: 123, i16: 123,
Expand All @@ -165,7 +174,7 @@ class OptionTests: XCTestCase {
XCTAssertEqual(reflected.f64, 123.4)
XCTAssertEqual(reflected.boolean, true)
}

func testStructWithOptionFieldsNone() {
let val = StructWithOptionFields(
u8: nil, i8: nil, u16: nil, i16: nil,
Expand All @@ -187,29 +196,28 @@ class OptionTests: XCTestCase {
XCTAssertEqual(reflected.f64, nil)
XCTAssertEqual(reflected.boolean, nil)
}

func testEnumWhereVariantsHaveNoData() {
let val = OptionEnumWithNoData.Variant2
let reflectedSome = rust_reflect_option_enum_with_no_data(val)
let reflectedNone = rust_reflect_option_enum_with_no_data(nil)

switch reflectedSome! {
case .Variant2:
break;
default:
XCTFail()
}

XCTAssertNil(reflectedNone)
}

func testOptionStruct() {
let val = OptionStruct(field: 123)
let reflectedSome = rust_reflect_option_struct_with_no_data(val)
let reflectedNone = rust_reflect_option_struct_with_no_data(nil)

XCTAssertEqual(reflectedSome!.field, 123)
XCTAssertNil(reflectedNone)
}
}

2 changes: 1 addition & 1 deletion crates/swift-bridge-ir/src/bridged_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1499,7 +1499,7 @@ impl BridgedType {
//
// Say we have an extern Rust function `create_string(str: &str) -> String`.
// It would be called using `__swift_bridge__$create_string(str)`
// But that would return a pointer to a swift_bridge::RustString.. So we need to convert that
// But that would return a pointer to a swift_bridge::RustString. So we need to convert that
// to something Swift can make use of.
// The final result on the Swift side would be:
//
Expand Down
78 changes: 62 additions & 16 deletions crates/swift-bridge-ir/src/bridged_type/bridged_opaque_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,11 +311,24 @@ impl BridgeableType for OpaqueForeignType {
}
}
} else {
quote! {
if let Some(val) = #expression {
Box::into_raw(Box::new(val))
} else {
std::ptr::null_mut()
match self.host_lang {
HostLang::Rust => {
quote! {
if let Some(val) = #expression {
Box::into_raw(Box::new(val))
} else {
std::ptr::null_mut()
}
}
}
HostLang::Swift => {
quote! {
if let Some(val) = #expression {
val.0.cast()
} else {
std::ptr::null_mut()
}
}
}
}
}
Expand Down Expand Up @@ -414,7 +427,14 @@ impl BridgeableType for OpaqueForeignType {
expression = expression,
)
} else {
format!("{{ if let val = {expression} {{ val.isOwned = false; return val.ptr }} else {{ return nil }} }}()", expression = expression,)
match self.host_lang {
HostLang::Rust => {
format!("{{ if let val = {expression} {{ val.isOwned = false; return val.ptr }} else {{ return nil }} }}()", expression = expression,)
}
HostLang::Swift => {
format!("{{ if let val = {expression} {{ return Unmanaged.passRetained(val).retain().toOpaque() }} else {{ return nil }} }}()")
}
}
}
}

Expand Down Expand Up @@ -479,11 +499,28 @@ impl BridgeableType for OpaqueForeignType {
}
}
} else {
quote! {
if #expression.is_null() {
None
} else {
Some(unsafe { * Box::from_raw(#expression) } )
match self.host_lang {
HostLang::Rust => {
quote! {
if #expression.is_null() {
None
} else {
Some(unsafe { *Box::from_raw(#expression) } )
}
}
}
HostLang::Swift => {
let ty = &self.ty;
quote! {
{
let val = #expression;
if val.is_null() {
None
} else {
Some(#ty(val.cast()))
}
}
}
}
}
}
Expand Down Expand Up @@ -545,11 +582,20 @@ impl BridgeableType for OpaqueForeignType {
)
} else {
let type_name = self.swift_name();
format!(
"{{ let val = {expression}; if val != nil {{ return {type_name}(ptr: val!) }} else {{ return nil }} }}()",
expression = expression,
type_name = type_name
)
match self.host_lang {
HostLang::Rust => {
format!(
"{{ let val = {expression}; if val != nil {{ return {type_name}(ptr: val!) }} else {{ return nil }} }}()",
expression = expression,
type_name = type_name
)
}
HostLang::Swift => {
format!(
"{{ if let val = {expression} {{ return Unmanaged<{type_name}>.fromOpaque(val).takeRetainedValue() }} else {{ return nil }} }}()"
)
}
}
}
}

Expand Down
1 change: 0 additions & 1 deletion crates/swift-bridge-ir/src/codegen/codegen_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ mod derive_struct_attribute_codegen_tests;
mod extern_rust_function_opaque_rust_type_argument_codegen_tests;
mod extern_rust_function_opaque_rust_type_return_codegen_tests;
mod extern_rust_method_swift_class_placement_codegen_tests;
mod extern_swift_function_opaque_swift_type_return_codegen_tests;
mod function_attribute_codegen_tests;
mod generic_opaque_rust_type_codegen_tests;
mod opaque_rust_type_codegen_tests;
Expand Down

0 comments on commit 636fa27

Please sign in to comment.