CO3: Towards the Optimal FFI

I've recently published a crate that aims to forever change how you think about FFI in Rust.

I've worked on it over the span of 3 years. I thought a good product wouldn't require advertisement but the big problem is still getting visibility and user adoption. What would make you more likely to adopt? What features do you find missing?

Some seem to have a problem with it, so a full disclosure is that yes, LLM generated code was used a lot in the last 6months of development or I would have spent another 3 years before publishing this work.

I would start with a brief summary on how your framework is different from previous work and why that is better.

The main thing that strikes me about that article (other than the odd puffery about it being the most amazing thing ever) is that it positions this as FFI, that is, to interoperate with other languages, without actually showing any other languages (at least as far as I got). If you're going to have a bunch of magic rules to make it easier to talk to C safely, it better be really clear and obvious what the C side looks like (especially when in many FFI situations you won't actually have control of the C interface)

Having some magic non-zero-cost abstraction does seem like it could be quite valuable... as an ABI for Rust to talk to itself across dynamic boundaries. I'll need to see something more convincing that it is actually desirable in a real FFI situation where, of course, it's inherently exceedingly unsafe even if everything is nicely matched up type-wise due to lifetimes, thread safety, and many other very important details are only documented (if you're lucky) and not representable in the language itself.

Thank you for the review.

other than the odd puffery about it being the most amazing thing ever

Noted. I understand that can be off putting.

it positions this as FFI, that is, to interoperate with other languages, without actually showing any other languages

I think of C ABI as the serialization format of FFI. When we write a JSON serializer in Rust, we don't talk about how another language will deserialize it. CO3 helps Rust communicate with the language boundary through C stable ABI regardless of who's listening on the other side.

However, your complaint is not missed and I think a solution can be implemented on top of CO3 that would connect a language of your choice with Rust. This is something to explore in the future.

If you're going to have a bunch of magic rules to make it easier to talk to C safely,

I'd say that you're being a bit too dismissive here. Any sufficiently advanced technology is seen as magic. There are really good reasons why syntax looks the way it does inside ffi!. One of the design goals was to make it look just like regular Rust but describing FFI required some extensions. I was really careful to make every extension follow the aesthetic of the Rust language.

I'm actually in the process writing another article to specifically address the "magic" syntax. I think this introductory article is too overwhelming.

it better be really clear and obvious what the C side looks like (especially when in many FFI situations you won't actually have control of the C interface)

If Rust talking to itself over the ABI boundary through CO3 there should be no issues. The declarations will match because you write them only once inside one ffi! block that is used on both export or import. This was another one of the design goals that API of your library should look the same whether you link to it as rlib or cdylib. The idea is that you write your crate in Rust and the FFI glue is generated directly out of that, no additional work required. CO3 gets you quite far, but some differences just cannot be abstracted away. This use-case is like really safe.

If Rust is talking to an existing C library then yes, you are responsible to correctly describe the FFI declarations. The other major design goal was that you should be able to explicitly describe any existing FFI boundary, but obviously this is much more dangerous because safety is predicated on programmer's responsibility; it is not entirely compiler asserted. Having said this, my intention is to provide a checker tool that compares output of CO3 extern declarations with an existing C header to catch such dangerous declaration mistakes.

FFI is inherently exceedingly unsafe due to lifetimes, thread safety and many other very important details are only documented

FFI is indeed inherently unsafe and many things just can't be encoded in the type system. CO3 should generally reject lifetime flowing from one fn arg into another unless you explicitly opt-into. The rule is that, by default, any pointer is considered valid only for the duration of the fn call.

Although I mention the conditions under which CO3 provides safety I should emphasize it more. I do think CO3 helps with safety and readability a lot

I'll need to see something more convincing that it is actually desirable in a real FFI situation

I really appreciate you taking the time for writing the critique and I'd love to get an opportunity to convince you further. In the article I mention the work on rs-odbc which might be an interesting dive in. Also, I actually went around some no-name crates I could find and opened PRs to transition them to CO3. This helped me catch some new FFI idioms that CO3 didn't support but now does.

This might simply be a terminology issue then: while you currently need to use FFI features to build a Rust to Rust ABI that's stable across versions, an "FFI library" implies the focus is on one that supports building an Interface to Foreign Functions.

Since the mechanism is intentionally about defining an FFI interface even if the focus is primarily for stable dynamic linking use-cases, calling this an FFI library isn't necessarily an incorrect description, but I'd make sure to quickly address it in an introduction when establishing what your focus is.

Just to be careful, I want to clarify that my statements of puffery or magic are not saying those things are actually inherently bad. The former is mostly just strange when compared to how absurdly understated many libraries are when describing themselves: for example the fairly uniquely designed and hugely popular serde describes itself without nearly any qualitative statements at all, simply saying it's a library for serialization, then a quick summary of the design. Likewise "magic" simply means anything getting done without the mechanism or underlying behavior being obvious: this is great when that isn't important and bad when it is. My statement there was just that for ABI usage the magic is fine, but for matching an existing FFI API you would want to avoid any magic for it to be really obvious that it's correctly describing the external API. Whether that's actually a problem for your library depends on how obvious the actual transformations being applied are, and how well you document them: unfortunately those are both subjective so it might hard to completely escape claims of magic here.

My statement there was just that for ABI usage the magic is fine, but for matching an existing FFI API you would want to avoid any magic for it to be really obvious that it's correctly describing the external API.

I think a really good way of thinking about CO3 is that every type found in any position inside the ffi! macro is represented by its C-companion with stable ABI. It's like knowing what a type Derefs to but for every type that you see.

It was my assumption that when interfacing with existing C code a programmer always wants to exit into safe Rust code and not deal with those weird intermediary types that exist at the boundary. CO3 removes all that bloat and jumps straight into Rust at the price of making the boundary less obvious to be correct.

The former is mostly just strange when compared to how absurdly understated many libraries are when describing themselves.

Your point is well-taken. I was trying not to leave an impression that what I'm presenting is a prototype. I postponed the release of CO3 to the point where I can honestly say this.

It seems that your library has some nice (i.e. ergonomic, safe) properties and provides features which people commonly reach for when working with FFI. However, you make a pretty strong claim: From the article:

I hope that, by the end of this article, I will have justified a strong claim that this is not yet another FFI framework, but a general model that unifies all attempts to solve the bidirectional interfacing and mapping of types between Rust and the C ABI.

I don't think anything in the article supports this claim. It feels like it's just a collection of features, like a "toolbox" style crate, of things which FFI implementations need.

  • what are the other "attempts" to solve this problem? Can you broadly categorize them?
  • how does your approach unify those attempts? is the functionality provided by your crate a superset of all other crates? Does your crate supersede other crates by providing a different functionality which can replace those crates?
  • how does the generated code differ from what one would write by hand?
  • is your crate user-extensible?

First of all, your reply is greatly appreciated.

However, you make a pretty strong claim

Isn't it more fun that way? :grin:

It feels like it's just a collection of features, like a "toolbox" style crate, of things which FFI implementations need.

In my view CO3 is a Rust language extension to describe the FFI boundary. It is a safe abstraction of a functionality . What else would it be but a collection of features? This is why I ask what more would you like to see that CO3 isn't offering

how does your approach unify those attempts? is the functionality provided by your crate a superset of all other crates? Does your crate supersede other crates by providing a different functionality which can replace those crates?

I hint at this in the title. The type mapping Rust <-> C is optimal in the sense that it can literally map arbitrary Rust type into its corresponding C type and describe it perfectly at the boundary in a non-surprising fashion. And when I say arbitrary, I really mean for any you can express in the Rust type system.

Try to think of a most outlandish type that you can. You could define some new type in your crate and it will get a perfectly specialized mapping for its &MyType, or &mut MyType, or `Option, etc. This is because types are categorized by their relevant properties and then blanket implementations are emitted targeting a specific selection of those properties. Without going into this claim too deep, I'll just give some simpler examples:

  • Box<bool> maps to stable CBox<CBool> which represents *mut u8.
  • &mut u32 maps to stable CRefMut<u32, true> which represents exclusive mut pointer
  • &UnsafeCell<[u32]> becomes, again stable, CWideRefMut<UnsafeCell<[u32]>, false> which is a structure holding non-exclusive mut data ptr + len

This is the hard part, everything else is sugar on top.

Since Rust types appear as their perfect counterparts in the C headers after a header generator run, this information(stored in types or type alias names) can now be used to generate bindings in another language, again perfectly and eliminate all sorts of checks at the boundary while the access remains safe.

So, it is by definition, a superset.

ffi! macro just wraps this. You can think of it as a module inside which every type is replaced by it's C-companion type. ffi! makes the values flow seamlessly back-and-forth.

how does the generated code differ from what one would write by hand?

it shouldn't differ because it's a zero-cost abstraction. The type conversions are literally perfect. What UB you can be protected from, you will be.

is your crate user-extensible?

well, of course. Users can define their own Rust types and functions, derive ReprC for
custom types, and configure conversions and ffi! declarations. You can always implement traits by hand and you can use co3::encode/co3::decode to convert between Rust type and it's stable C representation.