chinedufn / swift-bridge

swift-bridge facilitates Rust and Swift interop.
https://chinedufn.github.io/swift-bridge
Apache License 2.0
842 stars 62 forks source link

Result returns translating incorrectly? #260

Closed PrismaPhonic closed 8 months ago

PrismaPhonic commented 8 months ago

I'm not sure if I'm just doing something wrong but it appears that functions which return results aren't translating to Swift in a way that swift is happy with.

Do I need a special macro declaration on Error types?

Here's the error from swift:

Invalid conversion from throwing function of type '(RustStr) throws -> FileWorkoutManager' to non-throwing function type '(RustStr) -> FileWorkoutManager'

Here's the declaration:

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

        fn new_from_db_filepath_str(filepath: &str) -> Result<FileWorkoutManager, WPError>;

Here's the generated swift code:

public func new_from_db_filepath_str<GenericToRustStr: ToRustStr>(_ filepath: GenericToRustStr) throws -> FileWorkoutManager {
    return filepath.toRustStr({ filepathAsRustStr in
        try { let val = __swift_bridge__$new_from_db_filepath_str(filepathAsRustStr); if val.is_ok { return FileWorkoutManager(ptr: val.ok_or_err!) } else { throw WPError(ptr: val.ok_or_err!) } }()
    })
}

I'm getting that error for every single function I've declared with a Result return.

PrismaPhonic commented 8 months ago

I get the same on other methods that take an &str and return a Result.

It looks like the other Result return errors are that WPError does not conform to Error (which makes me wonder if I need a special macro declaration on that type)

chinedufn commented 8 months ago

Closing in favor of https://github.com/chinedufn/swift-bridge/issues/150

For now you have to write this on the Swift side (assuming WPError is thread safe, or never gets passed to another thread):

 extension WPError: @unchecked Sendable {} 
 extension WPError: Error {} 
PrismaPhonic commented 8 months ago

I think a challenge there is that with my project setup I have a swift library get auto generated from my FFI crate which would overwrite that - but thank you for linking to the other issue