iroha icon indicating copy to clipboard operation
iroha copied to clipboard

support `ffi_export` on trait implementations

Open mversic opened this issue 2 years ago • 1 comments

ffi_export attribute can be attached on inherent impls. This is not a hard limitation, this attribute could be made to support trait impls as well. This is not a very difficult thing to do but requires the macro library to support parsing of associated types.

If you take a look at data_model::name you can see that Name__from_str is implemented manually and is essentially a wrapper around FromStr implementation for Name. Impls such as this could be generated with ffi_export as well like this:

#[ffi_export]
impl FromStr for Name {
    type Err = ParseError;

    fn from_str(candidate: &str) -> Result<Self, Self::Err> {
        Self::validate_str(candidate).map(|_| Self(ConstString::from(candidate)))
    }
}

which would generate, once macro is expanded, something like:

extern fn Name__from_str(candidate: <<&str> as TryFromReprC>::Source) -> iroha_ffi::FfiResult {
    // ... generated code ...
}

mversic avatar Jul 15 '22 11:07 mversic

after some thought, I'm not sure this is what should be done in case of every trait impl, at least not for the traits in the std.

  1. Traits in std that don't contain associated types should be implemented with gen_ffi_impl in iroha_ffi::handle which forces multiplexing and reduces the size of the dynamically linked executable (smartcontract).
  2. Traits in std that contain associated types can support implementation via ffi_export because their associated methods are most likely generic over the contained associated type. This is FromStr in the previous example
  3. User defined traits, having associated types or not, cannot be known ahead of time and for them it might make sense to offer implementation via ffi_export. However, if technically feasible, their implementations should also be multiplexed

mversic avatar Jul 25 '22 20:07 mversic