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

#[swift_bridge::bridge] macro forces module to be private #252

Closed gabbifish closed 3 months ago

gabbifish commented 9 months ago

I defined a transparent type in one ffi submodule:

// error.rs
#[swift_bridge::bridge]
pub mod ffi {
    #[swift_bridge(swift_repr="struct")]
    pub struct RuntimeError {
        pub error: String
    }
}

and tried to import it in another module:

// lib.rs
mod error

use error:ffi:RuntimeError;

but saw the following error for this line: use error:ffi:RuntimeError:

module `ffi` is private

It seems the #[swift_bridge::bridge] macro forces its module to be private--is this intentional, or can its private/public status be passed through?

chinedufn commented 9 months ago

Not intentional, we've just been adding things as we need them and you're the first to make note of this.

One workaround is to use pub use self::ffi::Foo from outside of mod foo to expose Foo to other module.


Supporting this should be easy though if you're interested. Roughly two lines of implementation code + a couple of tests.

Here's how one might add support for preserving the module's visibility, in case you or any future person wants to tackle this:

Potential Solution

Add a parsing test where we verify that we can store the module's visibility https://github.com/chinedufn/swift-bridge/blob/72e1759e0504e3a5a32587605c98e410f12ea9e7/crates/swift-bridge-ir/src/parse.rs#L164-L210


Add a codegen test where we confirm that the module's visibility is preserved in the generated Rust tokens:

Perhaps in a mod module_visibility_tests in here https://github.com/chinedufn/swift-bridge/blob/4fbd30f81085dc366bda3c0303eac66345de3ed9/crates/swift-bridge-ir/src/codegen/codegen_tests.rs#L30-L54


Add a field SwiftBridgeModule.visibility: syn::Visibility https://github.com/chinedufn/swift-bridge/blob/b07745108b0daa86255fbc30dc1bce7ce9c02eb5/crates/swift-bridge-ir/src/lib.rs#L59-L60


Then set the field during parsing visibility: item_mod.visibility https://github.com/chinedufn/swift-bridge/blob/72e1759e0504e3a5a32587605c98e410f12ea9e7/crates/swift-bridge-ir/src/parse.rs#L126-L127


Interpolate the visibility here #visibility #mod_name

https://github.com/chinedufn/swift-bridge/blob/d03f77295fb60bee9f1bbb67da9d1f49bc765966/crates/swift-bridge-ir/src/codegen/generate_rust_tokens.rs#L305


Verify that tests pass using cargo test -p swift-bridge-ir

gabbifish commented 9 months ago

Awesome! I'll try and get a PR open for this soon :)

jnbooth commented 3 months ago

Fixed in #284.