Skip to main content

weaveffi/
lib.rs

1//! WeaveFFI: write safe Rust, get a stable C ABI and bindings for 11
2//! languages.
3//!
4//! This is the one crate a Rust producer depends on. Tag the items you want
5//! to export, anywhere in the crate, and call [`export_runtime!`] once at
6//! the crate root. Every expansion emits the `extern "C"` functions the
7//! generated bindings call, marshalling each value through the audited
8//! runtime, so you never write `unsafe` glue. Every C symbol starts with the
9//! crate's name (`calculator_add` below).
10//!
11//! ```ignore
12//! /// The library's error domain. Its `Display` comes from the docs.
13//! #[weaveffi::error]
14//! #[derive(Debug)]
15//! pub enum MathError {
16//!     /// division by zero
17//!     DivisionByZero = 1,
18//! }
19//!
20//! /// Add two integers.
21//! #[weaveffi::export]
22//! pub fn add(a: i32, b: i32) -> i32 {
23//!     a + b
24//! }
25//!
26//! /// Divide, reporting division by zero through the ABI's error channel.
27//! #[weaveffi::export]
28//! pub fn div(a: i32, b: i32) -> Result<i32, MathError> {
29//!     a.checked_div(b).ok_or(MathError::DivisionByZero)
30//! }
31//!
32//! /// Parse an integer; any error converts into `weaveffi::Error`
33//! /// (`throws any`).
34//! #[weaveffi::export]
35//! pub fn parse(text: &str) -> Result<i64, weaveffi::Error> {
36//!     Ok(text.parse()?)
37//! }
38//!
39//! // The runtime symbols (memory, errors, cancel tokens), once per crate.
40//! weaveffi::export_runtime!();
41//! ```
42//!
43//! The attributes also embed the API in the built library, which is what
44//! `weaveffi generate` reads to emit the header and bindings, so the
45//! producer and the bindings can't drift: the bindings describe exactly what
46//! the library was compiled with. A library is one namespace: every
47//! exported name is unique across the crate.
48//!
49//! # What you get
50//!
51//! * [`macro@export`]: export a free function, or every `pub fn` of an
52//!   `impl` block of an interface (constructors return `Self`; methods take
53//!   `&self`). An `async fn` is asynchronous; a `Result`-returning function
54//!   throws its error type, a [`macro@error`] domain or an untyped error
55//!   ([`Error`], `String`, `std::io::Error`, ...). An `async fn` whose last
56//!   parameter is a [`CancelToken`] is cancellable.
57//! * [`macro@record`]: a struct crossing by value.
58//! * [`macro@enumeration`]: a C-style enum, or one with data-carrying
59//!   variants.
60//! * [`macro@interface`]: a reference-counted object type, passed as `&T`
61//!   or `Arc<T>` and returned as `Self`, `T`, or `Arc<T>`.
62//! * [`macro@error`]: an error domain, with a generated `Display` (from
63//!   `#[weaveffi(message = "...")]` templates or the variants' docs) and
64//!   `std::error::Error`.
65//! * [`macro@callback_interface`]: a trait the consumer implements, accepted
66//!   as `Arc<dyn Trait>` (or `Option<Arc<dyn Trait>>`).
67//! * [`macro@custom`]: a type that crosses as another (its repr), converted
68//!   with your functions; it may be a foreign type such as `uuid::Uuid`.
69//! * [`set_spawner`]: install the executor async exports run on.
70//! * [`export_runtime!`]: the runtime symbols and the crate's tag type,
71//!   once, at the crate root.
72//!
73//! # Features
74//!
75//! * `tokio` (default) runs exported `async fn`s on Tokio: the current
76//!   runtime when a launcher is called from inside one, otherwise a
77//!   multi-thread runtime created on first use. Without it, each async call
78//!   runs on a thread of its own. [`set_spawner`] overrides either. On
79//!   `wasm32` calls are polled inline.
80//! * `leak-check` counts live objects, callbacks, iterators, cancel tokens,
81//!   and runs, reported by `{prefix}_debug_live` so a test harness can
82//!   assert a consumer released everything.
83//! * `anyhow` lets a function return `Result<T, anyhow::Error>`.
84
85#![deny(missing_docs)]
86#![warn(clippy::missing_errors_doc)]
87#![warn(clippy::missing_panics_doc)]
88#![warn(clippy::missing_safety_doc)]
89#![warn(clippy::doc_markdown)]
90
91#[doc(hidden)]
92pub mod rt;
93
94#[doc(hidden)]
95pub use rt as __rt;
96
97/// An owned, lazily pulled iterator, returned by a function whose bindings
98/// see `iter<T>`. Build one from any iterator with [`Iter::new`].
99pub use __rt::Iter;
100
101/// The producer's handle on a consumer's cancel token, the final parameter
102/// of a cancellable `async fn`. When the consumer cancels, the runtime drops
103/// the function's future and completes the call with the cancelled code;
104/// poll [`is_cancelled`](CancelToken::is_cancelled) only for cooperative
105/// cleanup (work on other threads, say).
106pub use __rt::CancelToken;
107
108/// A consumer's callback-interface implementation failed. A callback
109/// method's error type converts from it (`E: From<ForeignError>`), and it's
110/// a valid error type itself.
111pub use __rt::ForeignError;
112
113/// An untyped error that any `std::error::Error` converts into with `?`.
114pub use __rt::error::Error;
115
116/// Install the process-wide executor exported `async fn`s run on. Call it
117/// once at startup, before the first async export is launched.
118pub use __rt::set_spawner;
119
120/// The executor hook [`set_spawner`] accepts.
121pub use __rt::Spawner;
122
123/// The type-erased `Send + 'static` future a [`Spawner`] receives.
124pub use __rt::BoxFuture;
125
126pub use weaveffi_macros::{
127    callback_interface, custom, enumeration, error, export, export_runtime, interface, record,
128};