Skip to content

Commit

Permalink
Support throwing initializers (#287)
Browse files Browse the repository at this point in the history
This PR implements throwing initializers. See: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/errorhandling/.

Here's an example of using this feature:

```rust
// Rust
#[swift_bridge::bridge]
mod ffi {
    enum ResultTransparentEnum {
        NamedField { data: i32 },
        UnnamedFields(u8, String),
        NoFields,
    }
    extern "Rust" {
        type ThrowingInitializer;
        #[swift_bridge(init)]
        fn new(succeed: bool) -> Result<ThrowingInitializer, ResultTransparentEnum>;
        fn val(&self) -> i32;
    }
}
```

```swift
// Swift
do {
    let throwingInitializer = try ThrowingInitializer(false)
} catch let error as ResultTransparentEnum {
    //...
} catch {
    //...
}
```
  • Loading branch information
NiwakaDev authored Aug 15, 2024
1 parent 495611b commit 1b547a5
Show file tree
Hide file tree
Showing 14 changed files with 315 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,27 @@ class ResultTests: XCTestCase {
XCTAssertEqual(UInt32(i), value.val())
}
}

/// Verify that we can use throwing initializers defined on the Rust side.
func testThrowingInitializers() throws {
XCTContext.runActivity(named: "Should fail") {
_ in
do {
let throwingInitializer = try ThrowingInitializer(false)
} catch let error as ResultTransparentEnum {
if case .NamedField(data: -123) = error {
// This case should pass.
} else {
XCTFail()
}
} catch {
XCTFail()
}
}
XCTContext.runActivity(named: "Should succeed") {
_ in
let throwingInitializer = try! ThrowingInitializer(true)
XCTAssertEqual(throwingInitializer.val(), 123)
}
}
}
52 changes: 52 additions & 0 deletions book/src/bridge-module/functions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,58 @@ do {

## Function Attributes

#### #[swift_bridge(init)]
Used to generate a Swift initializer for Opaque Types.

```rust
// Rust

#[swift_bridge::bridge]
mod ffi {
extern "Rust" {
type RegularInitializer;

#[swift_bridge(init)]
fn new() -> RegularInitializer;
}

extern "Rust" {
type FailableInitializer;

#[swift_bridge(init)]
fn new() -> Option<FailableInitializer>;
}

enum SomeError {
case1,
case2
}

extern "Rust" {
type ThrowingInitializer;

#[swift_bridge(init)]
fn new() -> Result<FailableInitializer, SomeError>;
}
}
```

```swift
// Swift

let regularInitializer = RegularInitializer()

if let failableInitializer = FailableInitializer() {
// ...
}

do {
let throwingInitializer = try ThrowingInitializer()
} catch let error {
// ...
}
```

#### #[swift_bridge(Identifiable)]

Used to generate a Swift `Identifiable` protocol implementation.
Expand Down
9 changes: 9 additions & 0 deletions crates/swift-bridge-ir/src/bridged_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ pub(crate) enum TypePosition {
FnReturn(HostLang),
SharedStructField,
SwiftCallsRustAsyncOnCompleteReturnTy,
ThrowingInit(HostLang),
}

/// &[T]
Expand Down Expand Up @@ -1177,6 +1178,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}
StdLibType::Null => "()".to_string(),
Expand All @@ -1193,6 +1195,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
},
StdLibType::Vec(ty) => match type_pos {
TypePosition::FnArg(func_host_lang, _) => {
Expand All @@ -1215,6 +1218,7 @@ impl BridgedType {
"UnsafeMutableRawPointer".to_string()
}
}
TypePosition::ThrowingInit(_) => unimplemented!(),
_ => {
format!(
"RustVec<{}>",
Expand Down Expand Up @@ -1243,6 +1247,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
shared_struct.ffi_name_string()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}
BridgedType::Foreign(CustomBridgedType::Shared(SharedType::Enum(shared_enum))) => {
Expand All @@ -1259,6 +1264,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}
}
Expand Down Expand Up @@ -1567,6 +1573,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
},
PointerKind::Mut => expression.to_string(),
},
Expand Down Expand Up @@ -1660,6 +1667,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
},
},
StdLibType::Str => match type_pos {
Expand All @@ -1677,6 +1685,7 @@ impl BridgedType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
},
StdLibType::Vec(_) => {
format!(
Expand Down
13 changes: 13 additions & 0 deletions crates/swift-bridge-ir/src/bridged_type/bridgeable_result.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::bridged_type::{BridgeableType, BridgedType, CFfiStruct, TypePosition};
use crate::parse::HostLang;
use crate::{TypeDeclarations, SWIFT_BRIDGE_PREFIX};
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, quote_spanned};
Expand Down Expand Up @@ -207,6 +208,7 @@ impl BuiltInResult {
}
"__private__ResultPtrAndPtr".to_string()
}
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down Expand Up @@ -253,6 +255,17 @@ impl BuiltInResult {
),
TypePosition::SharedStructField => todo!(),
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => todo!(),
TypePosition::ThrowingInit(lang) => {
match lang {
HostLang::Rust => format!(
"let val = {expression}; if val.tag == {c_ok_name} {{ self.init(ptr: val.payload.ok) }} else {{ throw {err_swift_type} }}",
expression = expression,
c_ok_name = c_ok_name,
err_swift_type = err_swift_type
),
HostLang::Swift => todo!(),
}
}
};
}

Expand Down
4 changes: 4 additions & 0 deletions crates/swift-bridge-ir/src/bridged_type/bridgeable_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ impl BridgeableType for BridgedString {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
"UnsafeMutableRawPointer?".to_string()
}
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down Expand Up @@ -130,6 +131,7 @@ impl BridgeableType for BridgedString {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
todo!()
}
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down Expand Up @@ -205,6 +207,7 @@ impl BridgeableType for BridgedString {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down Expand Up @@ -250,6 +253,7 @@ impl BridgeableType for BridgedString {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
format!("RustString(ptr: {}!)", expression)
}
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ impl BridgeableType for OpaqueForeignType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
} else {
match type_pos {
Expand All @@ -146,6 +147,7 @@ impl BridgeableType for OpaqueForeignType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}
}
Expand Down Expand Up @@ -396,6 +398,7 @@ impl BridgeableType for OpaqueForeignType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}
} else {
Expand All @@ -420,6 +423,7 @@ impl BridgeableType for OpaqueForeignType {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions crates/swift-bridge-ir/src/bridged_type/bridged_option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ impl BridgedOption {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
todo!()
}
TypePosition::ThrowingInit(_) => todo!(),
},
StdLibType::Vec(_) => {
format!(
Expand Down Expand Up @@ -397,6 +398,7 @@ impl BridgedOption {
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => {
unimplemented!()
}
TypePosition::ThrowingInit(_) => unimplemented!(),
}
}

Expand Down
2 changes: 2 additions & 0 deletions crates/swift-bridge-ir/src/bridged_type/built_in_tuple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ impl BridgeableType for BuiltInTuple {
}
TypePosition::SharedStructField => todo!(),
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => todo!(),
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down Expand Up @@ -227,6 +228,7 @@ impl BridgeableType for BuiltInTuple {
}
TypePosition::SharedStructField => todo!(),
TypePosition::SwiftCallsRustAsyncOnCompleteReturnTy => todo!(),
TypePosition::ThrowingInit(_) => todo!(),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,82 @@ void* __swift_bridge__$Foo$new(void);
.test();
}
}

/// Verify that we can create a Swift class with a throwing init.
mod extern_rust_class_with_throwing_init {
use super::*;

fn bridge_module_tokens() -> TokenStream {
quote! {
mod foo {
enum SomeErrEnum {
Variant1,
Variant2,
}
extern "Rust" {
type Foo;

#[swift_bridge(init)]
fn new() -> Result<Foo, SomeErrEnum>;
}
}
}
}

fn expected_rust_tokens() -> ExpectedRustTokens {
ExpectedRustTokens::Contains(quote! {
# [export_name = "__swift_bridge__$Foo$new"]
pub extern "C" fn __swift_bridge__Foo_new() -> ResultFooAndSomeErrEnum{
match super :: Foo :: new() {
Ok(ok) => ResultFooAndSomeErrEnum::Ok(Box::into_raw(Box::new({
let val: super::Foo = ok;
val
})) as *mut super::Foo),
Err(err) => ResultFooAndSomeErrEnum::Err(err.into_ffi_repr()),
}
}
})
}

const EXPECTED_SWIFT: ExpectedSwiftCode = ExpectedSwiftCode::ContainsAfterTrim(
r#"
public class Foo: FooRefMut {
var isOwned: Bool = true
public override init(ptr: UnsafeMutableRawPointer) {
super.init(ptr: ptr)
}
deinit {
if isOwned {
__swift_bridge__$Foo$_free(ptr)
}
}
}
extension Foo {
public convenience init() throws {
let val = __swift_bridge__$Foo$new(); if val.tag == __swift_bridge__$ResultFooAndSomeErrEnum$ResultOk { self.init(ptr: val.payload.ok) } else { throw val.payload.err.intoSwiftRepr() }
}
}
"#,
);

const EXPECTED_C_HEADER: ExpectedCHeader = ExpectedCHeader::ContainsAfterTrim(
r#"
typedef enum __swift_bridge__$ResultFooAndSomeErrEnum$Tag {__swift_bridge__$ResultFooAndSomeErrEnum$ResultOk, __swift_bridge__$ResultFooAndSomeErrEnum$ResultErr} __swift_bridge__$ResultFooAndSomeErrEnum$Tag;
union __swift_bridge__$ResultFooAndSomeErrEnum$Fields {void* ok; struct __swift_bridge__$SomeErrEnum err;};
typedef struct __swift_bridge__$ResultFooAndSomeErrEnum{__swift_bridge__$ResultFooAndSomeErrEnum$Tag tag; union __swift_bridge__$ResultFooAndSomeErrEnum$Fields payload;} __swift_bridge__$ResultFooAndSomeErrEnum;
"#,
);

#[test]
fn extern_rust_class_with_throwing_init() {
CodegenTest {
bridge_module: bridge_module_tokens().into(),
expected_rust_tokens: expected_rust_tokens(),
expected_swift_code: EXPECTED_SWIFT,
expected_c_header: EXPECTED_C_HEADER,
}
.test();
}
}
Loading

0 comments on commit 1b547a5

Please sign in to comment.