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

Fix `improper_ctypes` warning #254

Closed chinedufn closed 8 months ago

chinedufn commented 8 months ago

This commit fixes an improper_ctypes warning when bridging transparent structs that contain non FFI safe types.

While transparent structs that contained non FFI safe types were being passed in an FFI safe way before this commit, the Rust compiler could not know that what we were doing was FFI safe.

This commit uses #[allow(improper_ctypes)] to silence the lint.

Illustration

Before this commit the following bridge module:

#[swift_bridge::bridge]
mod ffi {
    struct SharedStruct {
        field: String
    }

    extern "Swift" {
        fn swift_func() -> SharedStruct;
    }
}

would lead to the following warning:

warning: `extern` block uses type `RustString`, which is not FFI-safe
 --> my_file.rs:4:12
  |
4 |     struct SharedStruct {
  |            ^^^^^^^^^^^^ not FFI-safe
  |
  = help: consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct
  = note: this struct has unspecified layout
  = note: `#[warn(improper_ctypes)]` on by default

This warning was a bit misleading in that it made it seem like the RustString needed a #[repr(C)] annotation.

The real issue was that the generated FFI representation type:

#[repr(C)]
struct __swift_bridge__SharedStruct {
    field: *mut std::string::RustString
}

was triggering a warning because the Rust compiler can't know that the non-FFI safe std::string::RustString is not being dereferenced on the Swift side.