Skip to main content

ulo_macros/
lib.rs

1//! Macros for `ulo`. Each expands to calls on the core's value-level API, which integration
2//! crates call directly; nothing here does what that API cannot.
3//!
4//! Errors are `syn::Error`s spanned on the offending token, and per-field and per-parameter
5//! assertions are emitted with `quote_spanned!`, so a compile error points at the field,
6//! parameter or attribute rather than at the macro invocation.
7
8mod construct;
9mod construct_attr;
10mod enhancers;
11mod handlers;
12mod module_attr;
13mod shared;
14
15use proc_macro::TokenStream;
16
17/// A type the container builds and injects into others: a provider, listed under a module's
18/// `providers`.
19///
20/// On a struct, every field is an injection point except one marked `#[injectable(default)]`,
21/// which is set from `Default`. On an impl block, the constructor is the fn named `new`, or the
22/// one marked `#[construct]`; its parameters are injection points, it may be `async`, and it may
23/// return `Self` or a `Result<Self, E>`. Both marks are read and removed, and a hidden import of
24/// each written beside the item lets an editor answer hover and go-to-definition on it. A mark is
25/// written bare or under `ulo`, `#[ulo::construct]`; any other qualifier is a compile error at it.
26///
27/// Arguments: a scope, `singleton`, `execution` or `transient` (none means `Auto`), and
28/// `timeout = <Duration expr>`, which writes `CONSTRUCT_TIMEOUT`. `Construct::hooks` is filled by
29/// probing the five lifecycle traits.
30///
31/// A type whose handlers a transport calls is a controller and takes `#[controller]` instead: an
32/// `#[injectable]` type is not a `Controller`, so `#[handlers]` on it and `#[module]`'s
33/// `controllers` both refuse it at compile time.
34#[proc_macro_attribute]
35pub fn injectable(attr: TokenStream, item: TokenStream) -> TokenStream {
36    construct::expand(construct::Kind::Injectable, attr.into(), item.into())
37        .unwrap_or_else(syn::Error::into_compile_error)
38        .into()
39}
40
41/// A controller: a type the container builds and its transports reach, through the handlers of
42/// its `#[handlers]` impl. Only another controller injects one; `wire()` refuses a read of a
43/// controller by any other binding.
44///
45/// It writes what `#[injectable]` writes, from a struct (`#[controller(default)]` marks a field
46/// set from `Default`) or from an impl block's `new` or `#[construct]` fn, and takes the same
47/// arguments: a scope and `timeout = <Duration expr>`. With no scope it is `Auto`: a singleton if
48/// nothing below it needs an execution, and built per call otherwise. It takes no route prefix;
49/// the module mounts a controller under one with `m.controller::<T>().at(prefix)`.
50///
51/// It also writes `impl ulo::Controller`, the mark that makes a type a controller, holding where
52/// the type implements `ulo::Handlers`, the impl `#[handlers]` writes, so a `#[controller]` type
53/// with no handler impl fails to compile here. `#[module]` accepts under `controllers` only a
54/// type implementing `Handlers` and refuses a `Controller` under `providers`, and `wire()` refuses
55/// a controller registered as a provider. A WebSocket gateway is a controller and takes
56/// `#[controller]` too. A `#[controller]` type whose handlers are mounted by hand, a gateway
57/// implementing `Gateway` among them, implements `Handlers` itself.
58///
59/// Rust resolves the attribute's path, and any path that reaches it is accepted, a re-export or
60/// a renamed dependency's name among them. The code it writes names `::ulo`: a crate depending on
61/// `ulo` under another name aliases it at its root, `extern crate framework as ulo;`. The same
62/// holds for `#[injectable]` and `#[handlers]`; the markers they read are written bare or under
63/// `ulo`.
64///
65/// On an impl block it stacks with `#[handlers]` in either order, so the constructor and the
66/// handlers can share one impl, `#[controller] #[handlers] impl Greeter { fn new(..) .. }`.
67#[proc_macro_attribute]
68pub fn controller(attr: TokenStream, item: TokenStream) -> TokenStream {
69    construct::expand(construct::Kind::Controller, attr.into(), item.into())
70        .unwrap_or_else(syn::Error::into_compile_error)
71        .into()
72}
73
74/// Marks the constructor inside an `#[injectable]` or `#[controller]` impl when it is not named
75/// `new`; the attribute on the impl reads and removes it. Anywhere else it is an error.
76#[proc_macro_attribute]
77pub fn construct(attr: TokenStream, item: TokenStream) -> TokenStream {
78    construct_attr::expand(attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
79}
80
81/// A module: `imports`, `providers`, `controllers`, `exports` and `global`, lowered to a
82/// `Module` impl whose `register` calls the value API. A struct with fields is a configured
83/// module, identified by value, and every `Secret<_>` field is registered for redaction.
84///
85/// Provider entries: `Type` (`provide::<Type>()`), `Type as dyn Trait` (`also_as`), `expr?`
86/// (`try_value`), `expr` (`value`), `with = |..| ..` (`with`, or `try_with` when the closure's
87/// output is a `Result`), `with(<scope>) = |..| ..` (`singleton`, `execution` or `transient`, or
88/// the `try_` form), a bare closure (shorthand for `with = closure`), `K: with = |..| ..` and
89/// `K: with(<scope>) = |..| ..` (the same binding, also bound under the trait key `K` with
90/// `also_as::<K>(|a| a)`), and `into dyn Trait: [..]` (contributions). A bare path reads as a
91/// type, so a constant is bound by value with a block, `{ LIMITS }`. Export entries: `Type` and
92/// `reexport Type`. A `controllers` entry implements `Handlers`, and through it `Controller`, by
93/// `#[controller]` and `#[handlers]` or by hand, and an entry under `providers`, by type or by
94/// value, implements no `Controller`; each mistake is a compile
95/// error at the entry. A closure under `providers` is not checked. A controller may be exported,
96/// for another controller to read.
97///
98/// A qualified binding is written with the `@` that reports print for a key. `Type @ Q`
99/// (`provide::<Type>().qualified::<Q>()`), `Type as dyn Trait @ Q` (both keys qualified), `expr @ Q`
100/// and `expr? @ Q` (`value` and `try_value`, then `.qualified::<Q>()`) take it in `providers`;
101/// `Type @ Q` and `reexport Type @ Q` take it in `exports` (`export_qualified`,
102/// `reexport_qualified`). A closure binding and an `into` item take none, and a second `@` on an
103/// entry is refused:
104///
105/// ```
106/// use ulo::{App, Dep, ExecOptions, injectable, module};
107///
108/// struct Primary;
109/// struct Replica;
110///
111/// #[derive(Debug, PartialEq)]
112/// struct Db(&'static str);
113///
114/// #[module(
115///     providers = [Db("primary") @ Primary, Db("replica") @ Replica],
116///     exports = [Db @ Primary, Db @ Replica],
117/// )]
118/// struct DbModule;
119///
120/// #[injectable]
121/// struct Writer {
122///     db: Dep<Db, Primary>,
123/// }
124///
125/// #[module(imports = [DbModule], providers = [Writer])]
126/// struct AppModule;
127///
128/// # #[tokio::main(flavor = "current_thread")]
129/// # async fn main() {
130/// let app = App::builder(AppModule).wire().unwrap().connect().await.unwrap();
131/// assert_eq!(app.get::<Writer>().await.unwrap().db.0, "primary");
132/// # }
133/// ```
134///
135/// `#[module]` writes what a module declares: imports, bindings of a type or a value, collection
136/// contributions, controllers and exports. A module that needs a readiness check (`.ready(..)`),
137/// a closure hook (`.on_init(..)`, `.on_destroy(..)`), a qualified closure binding or collection,
138/// the `enhancer` mark or module metadata such as `ulo_http::PreDispatch` implements `Module` by
139/// hand and calls those on the `ModuleDef`; it imports and is imported by `#[module]` modules
140/// like any other.
141///
142/// The key comes first in `K: with = ..` because a closure's body extends as far as it can: in
143/// `with = |cfg| RedisCache::new(cfg) as dyn Cache`, the `as` would parse as a cast inside the
144/// body. As with `X as dyn T`, the concrete type stays bound in the module too.
145///
146/// An `into K: [..]` list takes the forms `#[guards]` does, whatever `K` is: a type
147/// (`provide::<A>`), `value = expr` (a shared value; the macro writes the `Arc::new`),
148/// `with = |..| ..` (a factory written as in `#[guards]`: `with`, or `try_with` when its output
149/// is a `Result`) and `with(<scope>) = |..| ..` (`singleton`, `execution` or `transient`, or the
150/// `try_` form of each). It also takes `value = expr?` (`try_value`), whose `Err` `wire()`
151/// reports as it reports a providers entry's `expr?`. Every item lowers to `contribute::<K>()`.
152/// A global enhancer is a contribution under a role key, `into AnyGuard<Http>: [AuthGuard]`,
153/// which the core recognises by the key's type.
154///
155/// A `K` that is module metadata, a type implementing `ulo::Meta` such as `ulo_http::PreDispatch`
156/// or `ulo_http::Upgrades`, is not a contribution key: a transport reads it through
157/// `m.meta::<K>()`, so `into PreDispatch: [..]` fails to compile with an error naming `K`. Such a
158/// module is written by hand with `ModuleDef`.
159///
160/// `with` says how an item is built: by its closure. How long it lives is a separate argument,
161/// written as on `#[injectable]`. `with = ..` declares `Auto`: built once unless what the closure
162/// reads needs an execution, then built per execution. A provider contribution under `Auto` is a
163/// singleton, and `wire()` refuses one whose closure reads execution data. `with(singleton) = ..`,
164/// `with(execution) = ..` and `with(transient) = ..` write the scope instead.
165///
166/// Inference reads what a closure takes, not what it does. A closure that creates per-call state
167/// but reads nothing per call, such as `|| RequestTimer::start()`, is built once under `Auto`;
168/// it must be written `with(execution) = || RequestTimer::start()`.
169#[proc_macro_attribute]
170pub fn module(attr: TokenStream, item: TokenStream) -> TokenStream {
171    module_attr::expand(attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
172}
173
174/// A controller's handler impl, on every transport: writes `impl ulo::Handlers`, whose `mount`
175/// registers each handler, with the impl's `#[guards]`, `#[interceptors]`, `#[error_handlers]` and
176/// `#[meta]` as the controller tier and each method's as the method tier; every other item stays
177/// as written. A handler is a method carrying its transport's attribute, `#[ulo_http::get(..)]`,
178/// `#[ulo_rpc::message(..)]`, `#[ulo_ws::message(..)]` or `#[ulo_grpc::method]`. The controller
179/// itself is declared with `#[controller]`, on the struct or stacked on this impl in either order,
180/// where `new` or the `#[construct]` fn builds it, and a module that registers the controller
181/// mounts these handlers through `Handlers::mount`. `Handlers` requires `Controller`, so on a type
182/// that is not a controller, one declared `#[injectable]` among them, `#[handlers]` is a compile
183/// error naming `Controller`.
184///
185/// An impl-level `value = expr` is built once by `Handlers::mount` and shared by every handler
186/// it applies to, so a rate limiter declared on the impl limits the controller as a whole. A
187/// controller-level transport key that no handler's transport carries, `#[guards(htpp = ..)]`, is
188/// a compile error spanned on the key.
189///
190/// A handler behind `#[cfg]` is mounted, and its transport key counted, only in a build that
191/// compiles it. A scoped entry for a transport whose handlers all sit behind
192/// `#[cfg(feature = "rpc")]` goes in `#[cfg_attr(feature = "rpc", guards(rpc = ..))]` on the impl,
193/// which rustc evaluates before `#[handlers]` reads the impl's attributes.
194///
195/// `#[handlers]` reads a method's attributes through `cfg_attr`, at any depth:
196/// - `#[cfg_attr(feature = "x", ulo_http::get("/beta"))]` makes the method a handler only where
197///   the predicate holds, gated like a handler behind `#[cfg]`: mounted, and its key counted, only
198///   in that build. Elsewhere it is a plain method, dead code unless something calls it;
199///   `#[cfg(feature = "x")]` removes it instead.
200/// - `#[cfg_attr(feature = "x", guards(..))]`, and likewise `interceptors`, `error_handlers` and
201///   `meta`, on a handler applies its entries only where the predicate holds.
202/// - One `cfg_attr` may hold several of these beside unrelated attributes,
203///   `#[cfg_attr(feature = "x", ulo_http::get("/beta"), guards(AuthGuard), inline)]`;
204///   `#[handlers]` takes the enhancers and `meta` and leaves the rest in place.
205///
206/// `#[handlers]` reads and removes every enhancer and `#[meta]` attribute it takes, and writes
207/// beside the impl a hidden import of each, through which an editor answers hover and
208/// go-to-definition on the attribute's name, and on its `ulo` segment when it is written
209/// `#[ulo::guards]`. A marker is written bare or under `ulo`; any other qualifier,
210/// `#[framework::guards]` or a typo, is a compile error at the attribute.
211///
212/// A method carrying an attribute outside the language's own (`doc`, `allow`, `cfg`, `inline` and
213/// the like), the enhancer and `#[meta]` markers and `#[construct]`, such as
214/// `#[tracing::instrument]`, inside `cfg_attr` or not, is treated as a handler, so helpers go in a
215/// separate `impl` block. One such attribute written outside any `cfg_attr` makes the method a
216/// handler in every build; when every
217/// one sits inside a `cfg_attr`, the first decides, so the transport attribute goes first. A
218/// transport attribute inside `cfg_attr` beside another attribute macro outside one fails to
219/// compile where the predicate fails. A handler takes `&self`, or `self: Arc<Self>` for a reply
220/// that outlives the call, and declares no type or const parameter; the controller itself may be
221/// generic.
222#[proc_macro_attribute]
223pub fn handlers(attr: TokenStream, item: TokenStream) -> TokenStream {
224    handlers::expand(attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
225}
226
227/// Guards for every handler of a `#[handlers]` impl, or for one method: by type (`AuthGuard`),
228/// transport-scoped by type (`http = AuthGuard`), by value (`value = expr`), or by closure
229/// (`with = |u: Ext<CurrentUser>| ..`). Read and removed by `#[handlers]`, so on the impl it goes
230/// below `#[handlers]`; on a method it may sit inside `cfg_attr`; anywhere else it is an error.
231///
232/// On the impl, an entry applies to every handler and must have the role for each handler's
233/// transport; `http = AuthGuard` limits it to that transport's handlers. `value = expr` is built
234/// once and shared: on a method by that handler's calls, on the impl by every handler it applies
235/// to.
236///
237/// A closure is written synchronously, its parameters injection points. `with` says only that
238/// the closure builds the guard; how long the guard lives is a separate argument, written as on
239/// `#[injectable]`. `with = ..` declares `Auto`: built once and shared unless what the closure
240/// reads needs an execution, then built per execution. `with(singleton) = ..`,
241/// `with(execution) = ..` and `with(transient) = ..` write the scope instead, and
242/// `http(with(execution) = ..)` limits one to a transport's handlers.
243///
244/// Inference reads what a closure takes, not what it does. A closure that creates per-call state
245/// but reads nothing per call, such as `|| RequestTimer::start()`, is built once under `Auto`;
246/// it must be written `with(execution) = || RequestTimer::start()`.
247#[proc_macro_attribute]
248pub fn guards(attr: TokenStream, item: TokenStream) -> TokenStream {
249    enhancers::marker("guards", attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
250}
251
252/// Interceptors, with the same forms as `#[guards]`.
253#[proc_macro_attribute]
254pub fn interceptors(attr: TokenStream, item: TokenStream) -> TokenStream {
255    enhancers::marker("interceptors", attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
256}
257
258/// Error handlers, with the same forms as `#[guards]`.
259#[proc_macro_attribute]
260pub fn error_handlers(attr: TokenStream, item: TokenStream) -> TokenStream {
261    enhancers::marker("error_handlers", attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
262}
263
264/// Declared metadata on a handler or on its `#[handlers]` impl: plain `Send + Sync + 'static`
265/// values, built once when the handler mounts, which guards and interceptors read through
266/// `cx.exec().handler()`. The method's declaration of a type wins over the impl's. Read and
267/// removed by `#[handlers]`, so on the impl it goes below `#[handlers]`; on a method it may sit inside
268/// `cfg_attr`; anywhere else it is an error.
269#[proc_macro_attribute]
270pub fn meta(attr: TokenStream, item: TokenStream) -> TokenStream {
271    enhancers::meta_marker(attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
272}
273
274/// Carries a handler's controller-tier and method-tier enhancers and metadata from `#[handlers]` to
275/// the transport's handler attribute, which consumes it (`ulo_handler_codegen::protocol`).
276/// Reaching expansion means no transport attribute consumed it.
277#[doc(hidden)]
278#[proc_macro_attribute]
279pub fn __handler(attr: TokenStream, item: TokenStream) -> TokenStream {
280    enhancers::unconsumed_handler(attr.into(), item.into()).unwrap_or_else(syn::Error::into_compile_error).into()
281}
282
283/// Invoked by a transport's generated mount function with its transport type, its transport key,
284/// the name of its `shared` parameter and the tokens `__handler` carried: expands to the two
285/// `EnhancerSpec`s for one handler, with one role assertion per enhancer naming the handler.
286#[doc(hidden)]
287#[proc_macro]
288pub fn __enhancer_specs(input: TokenStream) -> TokenStream {
289    enhancers::specs(input.into()).unwrap_or_else(syn::Error::into_compile_error).into()
290}