weaveffi_macros/lib.rs
1//! Procedural macros that turn safe, annotated Rust into the WeaveFFI C ABI.
2//!
3//! A producer tags the items it exports, anywhere in the crate, and calls
4//! `weaveffi::export_runtime!()` once at the crate root:
5//!
6//! ```ignore
7//! /// Add two integers.
8//! #[weaveffi::export]
9//! pub fn add(a: i32, b: i32) -> i32 {
10//! a + b
11//! }
12//!
13//! weaveffi::export_runtime!();
14//! ```
15//!
16//! Each attribute expands on its own. It emits the item's `extern "C"`
17//! functions, typed through the runtime's value traits (so rustc resolves
18//! every type wherever it's declared), and embeds the item's metadata frame
19//! and contract function in the library. `weaveffi generate` reads the
20//! frames back out of the built library, so the generated bindings describe
21//! exactly what the library was compiled with. Every C symbol starts with
22//! the crate's name (`CARGO_CRATE_NAME`), and a library is one namespace.
23//!
24//! # Attributes
25//!
26//! * [`macro@export`] on a function, or on an interface's `impl` block
27//! (whose `pub fn`s become constructors, methods, and statics; a
28//! `#[weaveffi(skip)]` member is left out).
29//! * [`macro@record`] on a struct with named fields.
30//! * [`macro@enumeration`] on a C-style enum or one with named-field
31//! variants.
32//! * [`macro@error`] on an error-domain enum with explicit positive codes.
33//! * [`macro@interface`] on a reference-counted object type.
34//! * [`macro@callback_interface`] on a trait the consumer implements.
35//! * [`macro@custom`] on a type alias or struct that crosses as another type.
36//! * [`export_runtime!`] for the runtime symbols and the crate's tag.
37
38#![deny(missing_docs)]
39
40use proc_macro::TokenStream;
41
42mod callback;
43mod common;
44mod function;
45mod runtime;
46mod shape;
47mod types;
48
49fn emit(
50 result: syn::Result<proc_macro2::TokenStream>,
51 item: proc_macro2::TokenStream,
52) -> TokenStream {
53 match result {
54 Ok(tokens) => tokens.into(),
55 // Keep the item, so its own errors and its uses still type-check
56 // (and an IDE still sees it), next to the macro's error.
57 Err(e) => {
58 let error = e.into_compile_error();
59 quote::quote!(#error #item).into()
60 }
61 }
62}
63
64/// Export a function, or every `pub fn` of an interface's `impl` block.
65///
66/// A function's parameters may be values (`T`), borrows (`&str`, `&[u8]`,
67/// `&Store`, `&Entry`, `Option<&T>`), or callback interfaces
68/// (`Arc<dyn Trait>`, `Option<Arc<dyn Trait>>`). It returns nothing, a
69/// value, a `weaveffi::Iter<T>` (lazily pulled), or a `Result` of one,
70/// whose error is a `#[weaveffi::error]` domain or an untyped error
71/// (`weaveffi::Error`, `String`, `std::io::Error`, ...). An `async fn` is
72/// asynchronous, and cancellable when its last parameter is a
73/// `weaveffi::CancelToken`.
74///
75/// In an `impl` block, a member with `&self` (or `self: Arc<Self>`) is a
76/// method, a synchronous one returning the type (`Self`, `Arc<Self>`, or a
77/// `Result` of either) a constructor, and any other a static (so an async
78/// factory is a static that returns the interface).
79#[proc_macro_attribute]
80pub fn export(attr: TokenStream, item: TokenStream) -> TokenStream {
81 let copy = proc_macro2::TokenStream::from(item.clone());
82 let parsed = syn::parse_macro_input!(item as syn::Item);
83 emit(function::expand(attr.into(), parsed), copy)
84}
85
86/// Declare a record: a struct with named fields that crosses the ABI by
87/// value (serialized in a value buffer).
88#[proc_macro_attribute]
89pub fn record(attr: TokenStream, item: TokenStream) -> TokenStream {
90 let copy = proc_macro2::TokenStream::from(item.clone());
91 let parsed = syn::parse_macro_input!(item as syn::ItemStruct);
92 emit(types::record(attr.into(), parsed), copy)
93}
94
95/// Declare an enum: C-style (every variant a unit, crossing as an `int32_t`)
96/// or rich (variants with named fields, crossing as a value buffer). A
97/// variant's discriminant is its `= value`, or one more than the previous
98/// variant's.
99#[proc_macro_attribute]
100pub fn enumeration(attr: TokenStream, item: TokenStream) -> TokenStream {
101 let copy = proc_macro2::TokenStream::from(item.clone());
102 let parsed = syn::parse_macro_input!(item as syn::ItemEnum);
103 emit(types::enumeration(attr.into(), parsed), copy)
104}
105
106/// Declare an error domain from an enum whose variants have explicit
107/// positive values (the stable codes) and optional named fields (the
108/// code's payload). The macro generates `Display` (each variant's
109/// `#[weaveffi(message = "...")]` template, which may name its fields in
110/// braces, else the first line of its docs) and `std::error::Error`, unless
111/// written `#[weaveffi::error(no_display)]`.
112#[proc_macro_attribute]
113pub fn error(attr: TokenStream, item: TokenStream) -> TokenStream {
114 let copy = proc_macro2::TokenStream::from(item.clone());
115 let parsed = syn::parse_macro_input!(item as syn::ItemEnum);
116 emit(types::error(attr.into(), parsed), copy)
117}
118
119/// Declare an interface: a reference-counted object type, which must be
120/// `Send + Sync`. Export its `impl` block with `#[weaveffi::export]`.
121#[proc_macro_attribute]
122pub fn interface(attr: TokenStream, item: TokenStream) -> TokenStream {
123 let copy = proc_macro2::TokenStream::from(item.clone());
124 let parsed = syn::parse_macro_input!(item as syn::ItemStruct);
125 emit(types::interface(attr.into(), parsed), copy)
126}
127
128/// Declare a callback interface: a `Send + Sync` trait whose `&self`
129/// methods the consumer implements. Producers accept one as
130/// `Arc<dyn Trait>` (or `Option<Arc<dyn Trait>>`). Every method returns
131/// `Result<T, E>` with `E: From<weaveffi::ForeignError>`; when `E` is a
132/// `#[weaveffi::error]` domain, the consumer's typed errors arrive as its
133/// variants.
134#[proc_macro_attribute]
135pub fn callback_interface(attr: TokenStream, item: TokenStream) -> TokenStream {
136 let copy = proc_macro2::TokenStream::from(item.clone());
137 let parsed = syn::parse_macro_input!(item as syn::ItemTrait);
138 emit(callback::expand(attr.into(), parsed), copy)
139}
140
141/// Declare a custom type,
142/// `#[weaveffi::custom(repr = R, lift = f, lower = g)] pub type Name = T;`
143/// (or on a struct): `T` crosses the ABI as `R` (bindings see `R`),
144/// converted with `f: fn(R) -> Result<T, E: Display>` on the way in (a
145/// failure is a marshalling error carrying the message) and
146/// `g: fn(&T) -> R` on the way out. `T` may be a foreign type, such as
147/// `uuid::Uuid`.
148#[proc_macro_attribute]
149pub fn custom(attr: TokenStream, item: TokenStream) -> TokenStream {
150 let copy = proc_macro2::TokenStream::from(item.clone());
151 let parsed = syn::parse_macro_input!(item as syn::Item);
152 emit(types::custom(attr.into(), parsed), copy)
153}
154
155/// Emit the runtime symbols every WeaveFFI library exports, prefixed with
156/// the crate's name (`{prefix}_abi_version`, `{prefix}_error_set`,
157/// `{prefix}_error_set_payload`, `{prefix}_error_clear`,
158/// `{prefix}_error_free`, `{prefix}_alloc`, `{prefix}_run_free`, the four
159/// `{prefix}_cancel_token_*` functions, and `{prefix}_debug_live`), and the
160/// crate's tag type. Invoke it exactly once, at the crate root.
161#[proc_macro]
162pub fn export_runtime(input: TokenStream) -> TokenStream {
163 runtime::expand(input.into())
164 .unwrap_or_else(syn::Error::into_compile_error)
165 .into()
166}