Skip to main content

id_effect_proc_macro/
lib.rs

1//! Procedural macros for the workspace `effect` crate.
2//!
3//! Doc links cannot use the `id_effect::…` prefix here: this crate defines an `effect` function, which
4//! shadows the `effect` crate name in rustdoc link resolution.
5#![allow(rustdoc::broken_intra_doc_links)]
6#![deny(missing_docs)]
7
8mod derive_fsm;
9mod derive_optics;
10mod derive_schema_parser;
11mod distributed_behavior;
12mod effect_data;
13mod effect_macro;
14mod effect_tagged;
15mod from_row;
16mod match_effect;
17mod provider_spec;
18mod repository;
19
20use proc_macro::TokenStream;
21
22/// Compiles and runs the README examples as doctests.
23#[cfg(doctest)]
24#[doc = include_str!("../README.md")]
25struct ReadmeDoctests;
26
27/// Derive macro: structural [`PartialEq`], [`Eq`], and [`Hash`] for Effect.ts-style data types.
28///
29/// Types implementing these impls automatically satisfy [`id_effect::schema::data::EffectData`] via the
30/// blanket implementation in the `effect` crate.
31#[proc_macro_derive(EffectData)]
32pub fn derive_effect_data(input: TokenStream) -> TokenStream {
33  effect_data::derive_effect_data(input)
34}
35
36/// Injects `pub _tag: &'static str`, an [`id_effect::match_::HasTag`] impl, and
37/// `EFFECT_TAGGED_TAG` on the struct (see generated inherent associated const).
38///
39/// Only supports structs with **named fields**. Place **above** `#[derive(EffectData, …)]`.
40#[proc_macro_attribute]
41pub fn effect_tagged(attr: TokenStream, item: TokenStream) -> TokenStream {
42  effect_tagged::expand(attr, item)
43}
44
45/// Derive an inherent `layer()` (an `id_effect::Layer` providing the service) from
46/// `#[provides(Service)]`. Re-exported by `id_effect` as `ProviderSpecDerive`.
47///
48/// `Struct::layer::<E>()` is a `Layer<HCons<Service, HNil>, E>` that needs nothing and never
49/// fails. The service value comes from, in order of precedence:
50///
51/// - `#[provides(Service, with = <constructor>)]` — `|| expr`, or a path such as `Self::build`
52///   called with no arguments. This is the recommended form: no `fn new() -> Service` (which
53///   trips `clippy::new_ret_no_self`) is needed.
54/// - `Self::default()` when the struct derives `Default` (the provider is its own service).
55/// - `Self::new()` otherwise.
56///
57/// `#[provides(Service, release = <finalizer>)]` makes it an `acquire_release` layer whose
58/// finalizer `release(Arc<Service>)` (an `Effect<(), Never, HNil>`) runs when the layer's scope
59/// closes. The 0.6 forms `|deps: &Env| ..` and `#[named("..")]` are compile errors.
60///
61/// ```ignore
62/// #[derive(Clone)]
63/// struct Counter(u32);
64///
65/// #[derive(ProviderSpecDerive)]
66/// #[provides(Counter, with = || Counter(42))]
67/// struct CounterLive;
68///
69/// let program = app().provide_layer(CounterLive::layer());
70/// ```
71#[proc_macro_derive(ProviderSpec, attributes(provides, named))]
72pub fn derive_provider_spec(input: TokenStream) -> TokenStream {
73  provider_spec::derive(input)
74}
75
76/// Enum match helper — prefix variant patterns with `EnumPath` for exhaustiveness checking.
77///
78/// ```ignore
79/// match_effect!(Color, value, {
80///     Red(n) => n,
81///     Green => 0,
82///     Blue => 1,
83/// })
84/// ```
85#[proc_macro]
86pub fn match_effect(input: TokenStream) -> TokenStream {
87  match_effect::expand(input)
88}
89
90/// Do-notation over an async body, building an `id_effect::Effect`.
91///
92/// `effect!({ body })` takes `R` from the expected type; `effect!(|r: &Caps| { body })` fixes
93/// `R = Caps` and binds `r: &Caps`. In the body, `~Cap` reads a capability (`&Arc<Cap>`),
94/// `~expr` runs a sub-effect over a part of `R` on the same fiber, widening its error (`Never`
95/// to anything, else `E: From<E2>`), and `~(a, b, ..)` joins up to 8 effects in parallel on
96/// child fibers. `?` on a `Result` fails the effect with its error. The body must be `Send`.
97///
98/// ```
99/// use id_effect::{Effect, Exit, Never, caps, effect, succeed};
100///
101/// struct Greeting(&'static str);
102///
103/// fn answer() -> Effect<u32> {
104///   succeed(42)
105/// }
106///
107/// fn hello() -> Effect<String, Never, caps!(Greeting)> {
108///   effect!({ format!("{}:{}", ~Greeting.0, ~answer()) })
109/// }
110///
111/// let out = hello().provide(Greeting("hi")).block_on();
112/// assert!(matches!(out, Exit::Success(ref s) if s == "hi:42"));
113/// ```
114#[proc_macro]
115pub fn effect(input: TokenStream) -> TokenStream {
116  effect_macro::effect::expand(input, false)
117}
118
119/// Like `effect!`, but builds an `id_effect::LocalEffect`, whose body may hold `!Send` values.
120/// `~expr` binds a `LocalEffect` or a `Send` `Effect` over a part of `R`.
121#[proc_macro]
122pub fn effect_local(input: TokenStream) -> TokenStream {
123  effect_macro::effect::expand(input, true)
124}
125
126/// `caps!(A, B, C)` is the environment type `HCons<A, HCons<B, HCons<C, HNil>>>`. A capability
127/// listed twice (compared by token) is one compile error at the repeat; the de-duplicated list
128/// is still emitted so no further errors cascade.
129#[proc_macro]
130pub fn caps(input: TokenStream) -> TokenStream {
131  effect_macro::caps::expand(input)
132}
133
134/// Derive field lenses and enum prisms for [`id_effect_optics`].
135#[proc_macro_derive(Optics, attributes(lens, prism, optional, optics))]
136pub fn derive_optics(input: TokenStream) -> TokenStream {
137  derive_optics::derive_optics(input)
138}
139
140/// Derive `id_effect_fsm::Fsm` (initial state + transition table) for a fieldless state enum.
141///
142/// Use it through the re-export `id_effect_fsm::Fsm`; the generated impl names
143/// `::id_effect_fsm` unless overridden with `crate = path`.
144///
145/// - Container: `#[fsm(event = EventType, initial = Variant, crate = path)]` — `event` is
146///   required; `initial` defaults to the first variant.
147/// - Variant: `#[fsm(on(Event => Target, ..))]`, repeatable. A bare `Event` resolves to
148///   `EventType::Event`; a multi-segment path is used as written.
149///
150/// Unknown targets, unknown `initial`, data-carrying variants, generic enums, and duplicate
151/// `(state, event)` edges are compile errors.
152///
153/// ```ignore
154/// use id_effect_fsm::Fsm;
155///
156/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
157/// enum DoorEvent { Open, Close }
158///
159/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Fsm)]
160/// #[fsm(event = DoorEvent, initial = Closed)]
161/// enum Door {
162///   #[fsm(on(Open => Opened))]
163///   Closed,
164///   #[fsm(on(Close => Closed))]
165///   Opened,
166/// }
167///
168/// let mut door = Door::state_machine();
169/// door.step(DoorEvent::Open).unwrap();
170/// assert_eq!(door.state(), Door::Opened);
171/// ```
172#[proc_macro_derive(Fsm, attributes(fsm))]
173pub fn derive_fsm(input: TokenStream) -> TokenStream {
174  derive_fsm::derive(input)
175}
176
177/// Derive an inherent `schema()` constructor and an [`id_effect::schema::HasSchema`] impl for a
178/// struct with named fields (JSON-shaped [`id_effect::schema::Unknown`] wire).
179///
180/// Rename a field on the wire with `#[schema("wire_name")]`.
181///
182/// The schema carries a `SchemaAst` (`schema().ast()`), so JSON Schema export (`schema-serde`)
183/// describes the struct: every field is `required` except `Option<_>` fields (missing or `null`),
184/// `i32` fields carry their range, and nested `HasSchema` fields are `$ref`s into `$defs` keyed by
185/// type path (recursive types terminate). Enums are not supported.
186///
187/// ```
188/// use id_effect::Schema;
189/// use id_effect::schema::{HasSchema, Unknown};
190///
191/// #[derive(Clone, Debug, PartialEq, Schema)]
192/// struct User {
193///   #[schema("user_name")]
194///   name: String,
195///   age: i64,
196/// }
197///
198/// let wire = User::schema().encode(User { name: "Ada".into(), age: 36 });
199/// let back = <User as HasSchema>::schema().decode_unknown(&wire).unwrap();
200/// assert_eq!(back.name, "Ada");
201/// assert!(matches!(wire, Unknown::Object(_)));
202/// ```
203#[proc_macro_derive(Schema, attributes(schema))]
204pub fn derive_schema(input: TokenStream) -> TokenStream {
205  derive_schema_parser::derive_schema(input)
206}
207
208/// Derive `id_effect_sql::FromRow` (decode a struct with named fields from an `SqlRow`).
209///
210/// Use it through the re-export `id_effect_sql::FromRow`; the generated impl names
211/// `::id_effect_sql` unless overridden with `#[from_row(crate = path)]`.
212///
213/// - Each field is `row.get::<FieldTy>(column)`; `Option<T>` fields decode NULL as `None`.
214///   The column is `#[from_row(rename = "col")]`, else the `#[derive(Schema)]` rename
215///   `#[schema("col")]`, else the field name.
216/// - `#[from_row(default)]`: a missing column is `Default::default()`.
217/// - `#[from_row(flatten)]`: the field is itself `FromRow`, decoded from the same row.
218/// - Container `#[from_row(schema)]`: decode the whole row with the type's `HasSchema` schema
219///   (`#[derive(Schema)]`), so refinements and brands run on database data and the issues come
220///   back as `SqlError::InvalidRow`; field `#[from_row(..)]` attributes are then errors.
221///
222/// ```ignore
223/// use id_effect_sql::FromRow;
224///
225/// #[derive(FromRow)]
226/// struct Todo {
227///   id: i64,
228///   #[from_row(rename = "title_text")]
229///   title: String,
230///   done_at: Option<id_effect_sql::jiff::Timestamp>,
231/// }
232/// ```
233#[proc_macro_derive(FromRow, attributes(from_row, schema))]
234pub fn derive_from_row(input: TokenStream) -> TokenStream {
235  from_row::derive(input)
236}
237
238/// Derive `id_effect_sql::Entity` (map a `#[derive(FromRow)]` struct to a table for
239/// `Repository<T>`; `id_effect_sql` feature `repository`).
240///
241/// Use it through the re-export `id_effect_sql::Entity`; the generated impl names
242/// `::id_effect_sql` unless overridden with `#[entity(crate = path)]`.
243///
244/// - Container: `table = ".."` (default: the type name in snake case), `tenant = "col"`,
245///   `soft_delete = "col"`, `scope = path` (a `fn() -> impl Into<Condition>`, repeatable).
246/// - Fields: exactly one `#[entity(id)]` (`#[entity(id, generated)]` when the database assigns
247///   it) and at most one `#[entity(version)]` integer (optimistic locking). Columns are the
248///   `FromRow` columns; `#[from_row(flatten)]` fields are rejected.
249///
250/// ```ignore
251/// use id_effect_sql::{Entity, FromRow};
252///
253/// #[derive(FromRow, Entity)]
254/// #[entity(table = "accounts", tenant = "org_id", soft_delete = "deleted_at")]
255/// struct Account {
256///   #[entity(id, generated)]
257///   id: i64,
258///   name: String,
259///   #[entity(version)]
260///   version: i64,
261/// }
262/// ```
263#[proc_macro_derive(Entity, attributes(entity))]
264pub fn derive_entity(input: TokenStream) -> TokenStream {
265  repository::derive(input)
266}
267
268/// Mark a process struct as a remotely spawnable behavior.
269///
270/// ```ignore
271/// #[distributed_behavior("counter")]
272/// struct Counter { ... }
273/// // Counter::BEHAVIOR_NAME == "counter"
274/// // Counter::register_behavior(&mut registry);
275/// ```
276#[proc_macro_attribute]
277pub fn distributed_behavior(attr: TokenStream, item: TokenStream) -> TokenStream {
278  distributed_behavior::expand(attr, item)
279}