Skip to main content

ice_rpc_macros/
lib.rs

1//! Procedural macros for the ice-rpc framework.
2//!
3//! The `#[service]` macro is the single entry point. It automatically
4//! generates the Proxy, Client, Server and the lifecycle code
5//! for an RPC service trait.
6
7#![cfg_attr(test, allow(clippy::unwrap_used))] // test code may panic
8mod codegen;
9mod entry;
10mod features;
11mod model;
12
13/// Golden comparison of the whole `#[service]` expansion.
14#[cfg(test)]
15mod golden_tests;
16
17// Private: the public value lives in `ice-rpc` (`types/consts.rs`) and must stay
18// identical. It caps the service/channel name; method names have no limit.
19pub(crate) const SERVICE_NAME_LEN: usize = 64;
20
21use proc_macro::TokenStream;
22use quote::quote;
23use syn::{Ident, ItemTrait, Type};
24
25use crate::features::Features;
26use crate::model::{ServiceAttr, ServiceModel};
27
28use crate::codegen::{
29    client::{
30        ClientGenInput, ClientMethodGenInput, ClientOnewayGenInput, gen_client_lifecycle,
31        gen_client_method, gen_client_oneway_method, gen_client_struct,
32    },
33    decoder::{DecoderGenInput, DecoderMethod, gen_decoder},
34    json::{
35        JsonGenInput, JsonMethod, gen_json_invoker_impl, gen_json_provider_from_request_fn,
36        gen_json_provider_from_response_fn, gen_json_provider_method,
37    },
38    lifecycle::{LifecycleGenInput, gen_lifecycle},
39    proxy::{
40        ProxyGenInput, ProxyMethodGenInput, ProxyOnewayGenInput, gen_proxy,
41        gen_proxy_blocking_method, gen_proxy_method, gen_proxy_oneway_call,
42        gen_proxy_oneway_method,
43    },
44    server::{ServerGenInput, gen_native_method, gen_native_oneway_method, gen_server},
45};
46
47/// The JSON view of the model's methods.
48///
49/// A narrow projection of [`ServiceModel`], **not** a second reading of the
50/// trait: the JSON converters need the same names and the same types as
51/// everybody else, so re-deriving them could only let the two disagree.
52fn json_methods(model: &ServiceModel) -> Vec<JsonMethod> {
53    model
54        .methods
55        .iter()
56        .map(|method| JsonMethod {
57            fn_name: method.fn_name.clone(),
58            var_name: method.var_name.clone(),
59            arg_names: method.arg_names.clone(),
60            arg_types: method.arg_types.clone(),
61            ok_type: method.ok_type.clone(),
62            err_type: method.err_type.clone(),
63            oneway: method.oneway,
64        })
65        .collect()
66}
67
68/// `#[service]` attribute macro: generates the Proxy, Client, Server, and the
69/// lifecycle code for an RPC service trait.
70///
71/// # Parameters
72///
73/// `"LogicalName"`, `version`, `group`, `max_slice_len`, `blocking`,
74/// `no_tracing` and `no_monitoring`.
75///
76/// `no_tracing` opts **this service** out of emitting `tracing` spans while the
77/// `tracing` feature of `ice-rpc` stays on: the call context is still installed
78/// (so `CallContext::current()` keeps its identity, its correlation id and the
79/// incoming W3C trace, and a call it emits keeps propagating), but the hop opens
80/// no span — and never hands its incoming context to the collector, since that
81/// adoption is consumed by the span of the hop.
82///
83/// `no_monitoring` opts **this service** out of the automatic observation while
84/// the `monitoring` feature of `ice-rpc` stays on: its decoder is not submitted
85/// to the link-time `DECODERS` registry, and its channel is submitted to
86/// `HIDDEN_CHANNELS` so `discover_channels` skips it. The generated decoder
87/// remains available for an explicit
88/// [`register`](ice_rpc::monitor::ServiceDecoder) — only the automatic path is
89/// off. The opt-out is at **channel** granularity: a service sharing a `group`
90/// hides the whole channel, so the services that must stay observable need a
91/// distinct group.
92///
93/// `max_slice_len` sizes the initial slice of the channel's publishers. It is a
94/// property of the **channel** (the `group`), so every service of a group must
95/// declare the same value; when omitted, the runtime default
96/// (`DEFAULT_MAX_SLICE_LEN`, 256) applies.
97///
98/// # The return type decides the kind of call
99///
100/// - `async fn f(..) -> Observable<T, E>` is a **request/response** method: the
101///   caller gets a stream, and the provider answers.
102/// - `async fn f(..);` — **no return type** — is a **one-way** method: the call is
103///   published once, nothing is answered, and no terminal event exists. The
104///   generated caller is therefore synchronous and returns
105///   `Result<bool, RpcError>`, where the `bool` says whether a subscriber took
106///   the sample; the provider handler runs and emits nothing.
107///
108/// There is no marker attribute and no implicit shape: a value-producing body
109/// cannot compile without its return type, so the two vocabularies cannot be
110/// confused by mistake. An explicit `-> ()` is refused with both alternatives
111/// named — drop the return type, or answer `Observable<(), E>`.
112///
113/// A one-way method is already synchronous, so the `blocking` parameter adds no
114/// `{method}_blocking` twin for it.
115///
116/// Automatically injects the async-trait attribute
117/// (`#[ice_rpc::codegen::async_trait::async_trait]`), `Send + Sync + 'static`
118/// as supertraits, and generates:
119/// - The `{Trait}Request` enum (rkyv-serializable)
120/// - The `{Trait}Client` struct (IPC consumer)
121/// - The `{Trait}Server` struct (IPC provider)
122/// - The `{Trait}Proxy` struct (Provider/Consumer smart node, plus the
123///   `ProviderJson` mode when the `json` block is on)
124/// - The `ServiceLifecycle`, `ServiceInit`, `ServiceNamed` implementations
125/// - The optional blocks its features ask for: the observer decoder
126///   (`monitoring`) and the JSON view (`json`) — the `impl JsonInvoker` every
127///   JSON transport dispatches to, the rkyv ↔ `serde_json::Value` converters,
128///   and the `ProviderJson` mode with its `provide_json()` constructor. They
129///   follow the Cargo features of this crate, read in one place
130///   (`Features::from_cfg`).
131///
132/// The JSON block is emitted whole whatever the deployment: the host half is
133/// reachable only from `provide_json()`, so a binary that never calls it does not
134/// link it. Splitting the block by feature would instead ask every crate that
135/// declares a service to know which process will call it, which a service cannot.
136#[proc_macro_attribute]
137pub fn service(attr: TokenStream, item: TokenStream) -> TokenStream {
138    expand_service_with(attr.into(), item.into(), Features::from_cfg()).into()
139}
140
141/// The body of [`service`], on `proc_macro2` tokens so that it stays testable.
142///
143/// A `proc_macro::TokenStream` cannot be built outside an actual expansion, so
144/// everything below the wrapper is written on the `proc_macro2` type: it is what
145/// lets the golden test in `tests/golden` expand a trait and read the result.
146/// `entry::expand_main` uses the same indirection.
147///
148/// `features` is the only thing that decides what is generated: no generator
149/// reads a Cargo feature, so the same call with the same set produces the same
150/// expansion in every build.
151fn expand_service_with(
152    attr: proc_macro2::TokenStream,
153    item: proc_macro2::TokenStream,
154    features: Features,
155) -> proc_macro2::TokenStream {
156    let service_attr = match syn::parse2::<ServiceAttr>(attr) {
157        Ok(service_attr) => service_attr,
158        Err(e) => return e.to_compile_error(),
159    };
160    let mut input_trait = match syn::parse2::<ItemTrait>(item) {
161        Ok(input_trait) => input_trait,
162        Err(e) => return e.to_compile_error(),
163    };
164
165    inject_trait_requirements(&mut input_trait);
166
167    // Read and validated once by the model; every generator works from it, so none
168    // can accept a signature another one refused.
169    let model = match ServiceModel::read(&service_attr, &input_trait) {
170        Ok(model) => model,
171        Err(e) => return e.to_compile_error(),
172    };
173
174    // Whether every method gets a synchronous twin, on client and proxy.
175    let blocking = service_attr.blocking;
176    // Whether this service opts out of emitting spans, wherever it is served.
177    let no_tracing = service_attr.no_tracing;
178    // Whether this service opts out of the automatic observation.
179    let no_monitoring = service_attr.no_monitoring;
180
181    let trait_name = &model.trait_name;
182    let visibility = &model.visibility;
183    let logical_name_lit = model.logical_name.clone();
184    let group_lit = model.group.clone();
185    let service_version = model.service_version;
186
187    // The default lives in `ice-rpc` (`DEFAULT_MAX_SLICE_LEN`), so the two crates
188    // cannot drift apart.
189    let max_slice_len = match model.max_slice_len {
190        Some(value) => quote! { #value },
191        None => quote! { ice_rpc::codegen::DEFAULT_MAX_SLICE_LEN },
192    };
193
194    let req_enum_name = &model.req_enum_name;
195    let client_name = &model.client_name;
196    let server_name = &model.server_name;
197    let proxy_name = &model.proxy_name;
198    let mode_name = &model.mode_name;
199    let init_default_name = &model.init_default_name;
200
201    // Declared once and read by both the client call and the provider registration,
202    // so the interface version can neither be dropped nor drift.
203    let service_ref = quote! { <#proxy_name>::SERVICE };
204    // Next to the identity: a span shows the name, the header only carries its hash.
205    let service_name = quote! { <#proxy_name>::SERVICE_NAME };
206
207    let mut req_variants = Vec::new();
208    let mut client_methods = Vec::new();
209    let mut proxy_blocking_methods = Vec::new();
210    let mut proxy_oneway_calls = Vec::new();
211    let mut server_native_methods = Vec::new();
212    let mut json_provider_methods = Vec::new();
213    let mut node_methods = Vec::new();
214    let mut decoder_methods: Vec<DecoderMethod> = Vec::new();
215
216    // One pass over the model; the discriminant is the position in the trait.
217    for (discriminant, method) in model.numbered_methods() {
218        let fn_name = &method.fn_name;
219        let var_name = &method.var_name;
220        let arg_names: Vec<&Ident> = method.arg_names.iter().collect();
221        let arg_types: Vec<&Type> = method.arg_types.iter().collect();
222
223        // Carries the arguments of every method, one-way ones included.
224        req_variants.push(quote! {
225            #var_name { #(#arg_names: #arg_types),* } = #discriminant
226        });
227
228        if method.oneway {
229            client_methods.push(gen_client_oneway_method(&ClientOnewayGenInput {
230                visibility,
231                fn_name,
232                var_name,
233                arg_names: &arg_names,
234                arg_types: &arg_types,
235                req_enum_name,
236                group: &group_lit,
237                service_ref: &service_ref,
238            }));
239
240            server_native_methods.push(gen_native_oneway_method(
241                proxy_name,
242                fn_name,
243                var_name,
244                &arg_names,
245                req_enum_name,
246                no_tracing,
247            ));
248
249            let proxy_oneway_input = ProxyOnewayGenInput {
250                fn_name,
251                arg_names: &arg_names,
252                arg_types: &arg_types,
253                mode_name,
254                visibility,
255                json_provider: features.json,
256            };
257            node_methods.push(gen_proxy_oneway_method(&proxy_oneway_input));
258            proxy_oneway_calls.push(gen_proxy_oneway_call(&proxy_oneway_input));
259            // Already synchronous: no `{method}_blocking` twin.
260        } else {
261            client_methods.push(gen_client_method(&ClientMethodGenInput {
262                visibility,
263                fn_name,
264                var_name,
265                arg_names: &arg_names,
266                arg_types: &arg_types,
267                ok_type: &method.ok_type,
268                err_type: &method.err_type,
269                req_enum_name,
270                group: &group_lit,
271                service_ref: &service_ref,
272                blocking,
273            }));
274
275            server_native_methods.push(gen_native_method(
276                proxy_name,
277                fn_name,
278                var_name,
279                &arg_names,
280                req_enum_name,
281                no_tracing,
282            ));
283
284            let proxy_method_input = ProxyMethodGenInput {
285                fn_name,
286                arg_names: &arg_names,
287                arg_types: &arg_types,
288                output_type: &method.output_type,
289                mode_name,
290                service_ref: &service_ref,
291                service_name: &service_name,
292                visibility,
293                json_provider: features.json,
294                no_tracing,
295            };
296            node_methods.push(gen_proxy_method(&proxy_method_input));
297            if blocking {
298                proxy_blocking_methods.push(gen_proxy_blocking_method(&proxy_method_input));
299            }
300        }
301
302        // JSON host side only: a build that merely consumes JSON must not carry them.
303        if features.json {
304            json_provider_methods.push(gen_json_provider_method(
305                proxy_name,
306                fn_name,
307                method.oneway,
308                no_tracing,
309            ));
310        }
311
312        // Collects the data for the generated decoder (`Display` + decoder).
313        if features.monitoring {
314            decoder_methods.push(DecoderMethod {
315                method_name: method.fn_name.to_string(),
316                var_name: var_name.clone(),
317                arg_names: method.arg_names.clone(),
318                ok_type: method.ok_type.clone(),
319                err_type: method.err_type.clone(),
320                oneway: method.oneway,
321            });
322        }
323    }
324
325    let client_input = ClientGenInput {
326        visibility,
327        client_name,
328        client_methods: &client_methods,
329    };
330    let client_struct = gen_client_struct(&client_input);
331    let client_lifecycle = gen_client_lifecycle(&client_input);
332
333    let server_input = ServerGenInput {
334        trait_name,
335        visibility,
336        server_name,
337        server_native_methods: &server_native_methods,
338        service_ref: &service_ref,
339    };
340    let server_output = gen_server(&server_input);
341
342    let proxy_input = ProxyGenInput {
343        trait_name,
344        visibility,
345        proxy_name,
346        client_name,
347        mode_name,
348        init_default_name,
349        logical_name_lit: &logical_name_lit,
350        group_lit: &group_lit,
351        max_slice_len: &max_slice_len,
352        service_ref: &service_ref,
353        node_methods: &node_methods,
354        blocking_methods: &proxy_blocking_methods,
355        oneway_calls: &proxy_oneway_calls,
356        json_provider: features.json,
357        json_provider_methods: &json_provider_methods,
358    };
359    let proxy_output = gen_proxy(&proxy_input);
360
361    let lifecycle_input = LifecycleGenInput {
362        trait_name,
363        proxy_name,
364        server_name,
365        mode_name,
366        logical_name_lit: &logical_name_lit,
367        group_lit: &group_lit,
368        max_slice_len: &max_slice_len,
369        json_provider: features.json,
370    };
371    let lifecycle_output = gen_lifecycle(&lifecycle_input);
372
373    // The three optional blocks: inputs always built, only the generator call is
374    // skipped, so nothing can drift into "declared but unused".
375    let json_methods: Vec<JsonMethod> = json_methods(&model);
376    let json_input = JsonGenInput {
377        visibility,
378        proxy_name,
379        req_enum_name,
380        methods: json_methods,
381    };
382    // Provider-side converters, reached only by `provide_json()`.
383    let (json_provider_from_request, json_provider_from_response) = if features.json {
384        (
385            gen_json_provider_from_request_fn(&json_input),
386            gen_json_provider_from_response_fn(&json_input),
387        )
388    } else {
389        (quote! {}, quote! {})
390    };
391
392    // One JSON view per service, whatever the transport: neither gateway carries
393    // generated code of its own. The reading policy travels as an argument.
394    let json_invoker = if features.json {
395        gen_json_invoker_impl(&json_input)
396    } else {
397        quote! {}
398    };
399
400    // Opt-in `monitoring` decoding: the only part forcing `Display` on every type.
401    let decoder_output = if features.monitoring {
402        let decoder_name = Ident::new(&format!("{trait_name}Decoder"), trait_name.span());
403        // `no_monitoring` keeps the decoder but hides its channel from automatic
404        // discovery; the channel is the `group`, resolved to the logical name when
405        // the service declares none.
406        let hidden_channel = no_monitoring.then_some(group_lit.as_str());
407        let decoder_input = DecoderGenInput {
408            visibility,
409            trait_name,
410            req_enum_name,
411            decoder_name: &decoder_name,
412            logical_name_lit: logical_name_lit.as_str(),
413            methods: &decoder_methods,
414            hidden_channel,
415        };
416        gen_decoder(&decoder_input)
417    } else {
418        quote! {}
419    };
420
421    // Unique symbol: a name collision fails at link time.
422    let collision_symbol = syn::Ident::new(
423        &format!("__ICE_RPC_SVC_{}", logical_name_lit.replace('-', "_")),
424        proc_macro2::Span::call_site(),
425    );
426
427    let generated = quote! {
428        #[repr(u8)]
429        // Named through the re-export, so no service crate needs `rkyv`.
430        #[derive(ice_rpc::codegen::rkyv::Archive, ice_rpc::codegen::rkyv::Deserialize, ice_rpc::codegen::rkyv::Serialize, Debug)]
431        #[rkyv(crate = ice_rpc::codegen::rkyv)]
432        #visibility enum #req_enum_name { #(#req_variants),* }
433
434        impl #proxy_name {
435            /// Identity of this service contract: its id inside the channel and
436            /// its interface version, declared once and shared by the generated
437            /// client and provider so the version cannot be lost between them.
438            #visibility const SERVICE: ice_rpc::codegen::ServiceRef =
439                ice_rpc::codegen::ServiceRef::new(
440                    ice_rpc::codegen::service_id_of(#logical_name_lit),
441                    #service_version,
442                );
443        }
444
445        #client_struct
446        #client_lifecycle
447
448        #server_output
449
450        #proxy_output
451
452        #lifecycle_output
453
454        #json_provider_from_request
455        #json_provider_from_response
456        #json_invoker
457
458        #decoder_output
459
460        #[doc(hidden)]
461        #[unsafe(no_mangle)]
462        static #collision_symbol: u8 = 0;
463    };
464
465    // Generated wrappers must not trip the consumer's `missing_docs` lint.
466    let generated = codegen::helpers::allow_missing_docs(generated);
467
468    let expanded = quote! {
469        #[allow(unexpected_cfgs)]
470        #input_trait
471
472        #generated
473    };
474
475    expanded
476}
477
478/// The injected path is `ice_rpc::codegen::async_trait::async_trait`, not the bare
479/// `async_trait`, so the service crate needs no `async-trait` dependency. A trait
480/// that already names the attribute — either spelling — is left untouched: the
481/// detection reads the last path segment, so `#[async_trait::async_trait]` and
482/// `#[ice_rpc::async_trait]` are both recognized.
483fn inject_trait_requirements(input_trait: &mut ItemTrait) {
484    let already_annotated = input_trait.attrs.iter().any(|attr| {
485        attr.path()
486            .segments
487            .last()
488            .is_some_and(|segment| segment.ident == "async_trait")
489    });
490    if !already_annotated {
491        input_trait
492            .attrs
493            .push(syn::parse_quote! { #[ice_rpc::codegen::async_trait::async_trait] });
494    }
495
496    // Compared as rendered tokens: a path-qualified `Send` counts as missing.
497    let present: Vec<String> = input_trait
498        .supertraits
499        .iter()
500        .map(|bound| quote!(#bound).to_string())
501        .collect();
502
503    for required in [quote!(Send), quote!(Sync), quote!('static)] {
504        if !present.contains(&required.to_string()) {
505            input_trait.supertraits.push(syn::parse_quote!(#required));
506        }
507    }
508}
509
510/// Bootstraps ice-rpc around an `async fn main`.
511///
512/// Generates a synchronous `fn main` that initializes ice-rpc, awaits the
513/// annotated body, then shuts ice-rpc down — **even when the body returns early
514/// via `?` or `return`**.
515///
516/// # Runtime
517///
518/// The macro bundles no runtime of its own; it only chooses how `main` is
519/// driven:
520/// - `#[ice_rpc::main]` → driven by `ice_rpc::rt::block_on`, which polls the
521///   body on the calling thread. The body still runs on the execution facade
522///   the crate is built with — `rt-async` (the default) provides the executor
523///   and the timers, `smol` its own — so this is *not* a runtime-free mode;
524/// - `#[ice_rpc::main(tokio)]` → a dedicated multi-thread tokio runtime;
525/// - `#[ice_rpc::main(pollster::block_on)]` → any user-provided `fn(Future) -> T`;
526/// - `#[ice_rpc::main(rt-none)]` → **no runtime at all**: the annotated function
527///   is a plain synchronous `fn main`, the body runs blocking, and ice-rpc is
528///   shut down with `shutdown_blocking` on the way out. This is the only mode
529///   that pulls in no async runtime.
530///
531/// # Example (blocking main)
532/// ```rust,ignore
533/// #[ice_rpc::main(rt-none)]
534/// fn main() {
535///     let proxy = ice_rpc::locator()
536///         .get_blocking::<MyServiceProxy>()
537///         .expect("the locator builds the proxy");
538///     let value = proxy.hello_blocking("Alice".into()).first_value_blocking();
539/// }
540/// ```
541///
542/// # Example Async main
543/// ```rust,ignore
544/// #[ice_rpc::main(tokio)]
545/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
546///     let proxy = ice_rpc::locator().get::<MyServiceProxy>().await?;
547///     // ...
548///     Ok(())
549/// }
550/// ```
551#[proc_macro_attribute]
552pub fn main(attr: TokenStream, item: TokenStream) -> TokenStream {
553    entry::expand_main(attr.into(), item.into())
554        .unwrap_or_else(|e| e.to_compile_error())
555        .into()
556}
557
558/// `#[payload]` attribute macro: derives the traits an ice-rpc service payload
559/// needs, **without the crate naming `rkyv`** — and without its author having to
560/// ask for `Debug`.
561///
562/// Expands to the annotated item preceded by
563/// `#[derive(ice_rpc::codegen::rkyv::Archive, ice_rpc::codegen::rkyv::Deserialize, ice_rpc::codegen::rkyv::Serialize)]`
564/// and `#[rkyv(crate = ice_rpc::codegen::rkyv)]`. The second attribute is what makes
565/// the dependency disappear: without it the rkyv derive expands against the
566/// default `::rkyv` path, and the service crate would have to declare it.
567///
568/// # `Debug`
569///
570/// The generated derivation carries `Debug` as well, **unless the item derives
571/// it already or opts out**. A payload type must be `Debug` to be observable: a
572/// service built with the `monitoring` feature derives `Debug` on its generated
573/// `{Trait}Request` enum, so an out-of-band observer can render the arguments.
574/// Supplying the trait here turns a puzzling error on generated code into a
575/// populated payload type.
576///
577/// It is never derived twice — that would be an `E0119`, two `impl Debug for X`.
578/// An item whose own `#[derive(..)]` names `Debug`, whatever the spelling
579/// (`std::fmt::Debug` included), keeps its derivation alone. A **hand-written
580/// `impl Debug`** is invisible to an attribute macro, which only sees the item it
581/// annotates, so such a type says so:
582///
583/// ```rust,ignore
584/// #[ice_rpc::payload(no_debug)] // `impl Debug` is written by hand
585/// pub struct Query {
586///     pub key: String,
587/// }
588/// ```
589///
590/// `Display` is deliberately not part of the set: it is not derivable — there is
591/// no `#[derive(Display)]` — and it has no canonical generated form. The
592/// framework prefers a hand-written `Display` when the type has one, and falls
593/// back to this `Debug` form otherwise.
594///
595/// # `Display`, for an error payload
596///
597/// `std::error::Error` requires `Debug` **and** `Display`, and `?` converts into
598/// a `Box<dyn Error>` only through that trait: a payload used as a service error
599/// therefore needs a `Display` as soon as it is propagated with `?` from a `main`
600/// returning `Result<(), Box<dyn Error>>`. `Debug` comes from the macro; the
601/// `Display` is asked for explicitly, because the *good* rendering — a sentence
602/// rather than a field dump — is the one the author writes by hand and an
603/// attribute macro cannot detect:
604///
605/// ```rust,ignore
606/// #[ice_rpc::payload(display)] // `impl Display` delegating to `Debug`
607/// pub enum MyError {
608///     NotFound,
609/// }
610/// ```
611///
612/// The generated implementation is `Debug::fmt`, so it must not be combined with
613/// a hand-written `impl Display` (an `E0119`), and `no_debug` is refused
614/// alongside it, since the delegation would have nothing to render.
615///
616/// Any `#[derive(..)]`, doc comment or other attribute already on the item is
617/// preserved — the generated derives are added in a **second** `#[derive(..)]`,
618/// which the compiler merges with the item's own.
619///
620/// # serde
621///
622/// When the `json` block is compiled in (the `json` feature of `ice-rpc`, which
623/// forwards to this crate), the macro also derives `Serialize` and `Deserialize`,
624/// through `ice_rpc::codegen::serde`: the JSON converters read every argument and
625/// response through them. Writing them by hand — and keeping them on the same
626/// feature as the codegen — used to be the caller's job; it is now the macro's, so
627/// the two cannot drift apart, and the service crate needs no `serde` dependency.
628///
629/// A `#[derive(serde::Serialize, serde::Deserialize)]` already on the item is left
630/// alone (a second derivation of one trait is an `E0119`), as is an item that
631/// carries its own `#[serde(crate = ..)]`. `no_serde` opts out for a type whose
632/// implementations are hand-written, which an attribute macro cannot see.
633///
634/// Applies to a `struct` or an `enum` only, and refuses an item that already
635/// carries an rkyv `crate` attribute, since this macro sets that attribute
636/// itself.
637///
638/// ```rust,ignore
639/// #[ice_rpc::payload] // rkyv derives + `Debug`
640/// pub struct Query {
641///     pub key: String,
642/// }
643/// ```
644#[proc_macro_attribute]
645pub fn payload(attr: TokenStream, item: TokenStream) -> TokenStream {
646    expand_payload(attr.into(), item.into(), Features::from_cfg()).into()
647}
648
649/// Options of [`payload`], read from the attribute's argument list.
650#[derive(Default)]
651struct PayloadOptions {
652    /// `no_debug`: never add the `Debug` derivation. For a type whose `Debug` is
653    /// written by hand — an `impl` an attribute macro cannot see — or one that
654    /// must stay free of the trait.
655    no_debug: bool,
656    /// `display`: additionally generate `impl Display`, delegating to `Debug`.
657    /// For an error payload that is propagated with `?` into a `Box<dyn Error>`,
658    /// which needs the trait.
659    display: bool,
660    /// `no_serde`: never add the `Serialize` / `Deserialize` derivations. Same
661    /// reason as `no_debug`: a hand-written impl is invisible to an attribute
662    /// macro, and a second one is an `E0119`.
663    no_serde: bool,
664}
665
666impl syn::parse::Parse for PayloadOptions {
667    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
668        let mut options = Self::default();
669        while !input.is_empty() {
670            let ident: Ident = input.parse()?;
671            if ident == "no_debug" {
672                options.no_debug = true;
673            } else if ident == "display" {
674                options.display = true;
675            } else if ident == "no_serde" {
676                options.no_serde = true;
677            } else {
678                return Err(syn::Error::new(
679                    ident.span(),
680                    format!("unknown parameter `{ident}` for #[ice_rpc::payload]"),
681                ));
682            }
683            if input.is_empty() {
684                break;
685            }
686            input.parse::<syn::Token![,]>()?;
687        }
688        Ok(options)
689    }
690}
691
692/// Body of [`payload`], kept on `proc_macro2` so a unit test can call it: a
693/// `#[proc_macro_attribute]` function is only invocable from the compiler.
694fn expand_payload(
695    attr: proc_macro2::TokenStream,
696    item: proc_macro2::TokenStream,
697    features: Features,
698) -> proc_macro2::TokenStream {
699    let options = match syn::parse2::<PayloadOptions>(attr) {
700        Ok(options) => options,
701        Err(error) => return error.to_compile_error(),
702    };
703
704    let parsed = match syn::parse2::<syn::Item>(item.clone()) {
705        Ok(parsed) => parsed,
706        Err(error) => return error.to_compile_error(),
707    };
708
709    // Whatever the item carries: `struct` and `enum` hold the same fields.
710    let (item_attrs, item_ident, item_generics) = match &parsed {
711        syn::Item::Struct(item) => (&item.attrs, &item.ident, &item.generics),
712        syn::Item::Enum(item) => (&item.attrs, &item.ident, &item.generics),
713        other => {
714            return syn::Error::new_spanned(
715                other,
716                "#[ice_rpc::payload] may only be applied to a struct or an enum",
717            )
718            .to_compile_error();
719        }
720    };
721
722    if item_attrs.iter().any(is_rkyv_crate_attr) {
723        return syn::Error::new_spanned(
724            &parsed,
725            "#[ice_rpc::payload] already sets `#[rkyv(crate = ..)]`; remove the one written on the item",
726        )
727        .to_compile_error();
728    }
729
730    // `Display` renders through `Debug`: refusing the pair here is clearer.
731    if options.display && options.no_debug {
732        return syn::Error::new_spanned(
733            &parsed,
734            "#[ice_rpc::payload] cannot combine `display` with `no_debug`: the generated `Display` renders through `Debug`",
735        )
736        .to_compile_error();
737    }
738
739    // `Debug` joins only when nothing else provides it (`E0119` otherwise), and a
740    // hand-written `impl` is out of sight, hence `no_debug`.
741    let debug = if options.no_debug || derives_trait(item_attrs, "Debug") {
742        quote! {}
743    } else {
744        quote! { Debug, }
745    };
746
747    // The JSON converters read everything through `serde`: both derivations follow
748    // the codegen switch and name `ice_rpc::codegen::serde`. A type that already
749    // derives either trait is left untouched (`E0119`, and it owns its `#[serde]`).
750    let add_serde = features.json
751        && !options.no_serde
752        && !derives_trait(item_attrs, "Serialize")
753        && !derives_trait(item_attrs, "Deserialize");
754
755    let serde_derives = if add_serde {
756        quote! {
757            ice_rpc::codegen::serde::Serialize,
758            ice_rpc::codegen::serde::Deserialize,
759        }
760    } else {
761        quote! {}
762    };
763
764    // Only meaningful next to the derivations above.
765    let serde_crate_attr = if add_serde {
766        quote! { #[serde(crate = "ice_rpc::codegen::serde")] }
767    } else {
768        quote! {}
769    };
770
771    // Opt-in: a hand-written `impl Display` cannot be detected, so the macro never
772    // guesses. `Debug::fmt` is the fallback shape, with the bounds it needs.
773    let display = if options.display {
774        let (impl_generics, ty_generics, where_clause) = item_generics.split_for_impl();
775        let mut predicates = where_clause
776            .map(|clause| clause.predicates.clone())
777            .unwrap_or_default();
778        predicates.push(syn::parse_quote!(
779            #item_ident #ty_generics: ::std::fmt::Debug
780        ));
781        quote! {
782            impl #impl_generics ::std::fmt::Display for #item_ident #ty_generics
783            where #predicates
784            {
785                fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
786                    ::std::fmt::Debug::fmt(self, f)
787                }
788            }
789        }
790    } else {
791        quote! {}
792    };
793
794    quote! {
795        #[derive(
796            ice_rpc::codegen::rkyv::Archive,
797            ice_rpc::codegen::rkyv::Deserialize,
798            ice_rpc::codegen::rkyv::Serialize,
799            #serde_derives
800            #debug
801        )]
802        #[rkyv(crate = ice_rpc::codegen::rkyv)]
803        #serde_crate_attr
804        #item
805        #display
806    }
807}
808
809/// Whether one of the item's **own** `#[derive(..)]` already asks for `trait_name`.
810///
811/// The trait is matched on the last path segment, so `#[derive(std::fmt::Debug)]`
812/// and `#[derive(serde::Serialize)]` count as well: what matters is that the trait
813/// is derived once, whatever path spelling names it.
814fn derives_trait(attrs: &[syn::Attribute], trait_name: &str) -> bool {
815    attrs
816        .iter()
817        .filter(|attr| attr.path().is_ident("derive"))
818        .any(|attr| {
819            let mut found = false;
820            // A malformed `derive` is left to the compiler; only the trait matters.
821            let _ = attr.parse_nested_meta(|meta| {
822                if meta
823                    .path
824                    .segments
825                    .last()
826                    .is_some_and(|segment| segment.ident == trait_name)
827                {
828                    found = true;
829                }
830                Ok(())
831            });
832            found
833        })
834}
835
836/// Whether one attribute is an rkyv `crate` attribute — `#[rkyv(crate = ..)]` or
837/// the bare `#[rkyv(crate)]` form.
838fn is_rkyv_crate_attr(attr: &syn::Attribute) -> bool {
839    if !attr.path().is_ident("rkyv") {
840        return false;
841    }
842    let mut found = false;
843    // A malformed attribute is left to the `rkyv` derive: only the key matters.
844    let _ = attr.parse_nested_meta(|meta| {
845        if meta.path.is_ident("crate") {
846            found = true;
847            // Consume `= <path>`, so `#[rkyv(crate)]` also parses cleanly.
848            let _ = meta.value().and_then(|value| value.parse::<syn::Path>());
849        }
850        Ok(())
851    });
852    found
853}
854
855#[cfg(test)]
856mod payload_tests {
857    use super::{Features, expand_payload};
858    use quote::quote;
859
860    /// Expands without any optional block, which is the state most assertions
861    /// below are written against.
862    ///
863    /// The set is explicit, never `Features::from_cfg()`: a test must not depend
864    /// on the features of the build that runs it.
865    fn expand(
866        attr: proc_macro2::TokenStream,
867        item: proc_macro2::TokenStream,
868    ) -> proc_macro2::TokenStream {
869        expand_payload(
870            attr,
871            item,
872            Features {
873                monitoring: false,
874                json: false,
875            },
876        )
877    }
878
879    /// Same, with the `json` block compiled in: the serde derivations belong to it.
880    fn expand_json(
881        attr: proc_macro2::TokenStream,
882        item: proc_macro2::TokenStream,
883    ) -> proc_macro2::TokenStream {
884        expand_payload(
885            attr,
886            item,
887            Features {
888                monitoring: false,
889                json: true,
890            },
891        )
892    }
893
894    /// The generated derivation alone — everything before the `#[rkyv(..)]` the
895    /// macro also emits. The item, and thus its own `#[derive(..)]`, comes after.
896    fn generated_derivation(out: &proc_macro2::TokenStream) -> String {
897        let rendered = out.to_string();
898        rendered
899            .split("# [rkyv")
900            .next()
901            .unwrap_or_default()
902            .to_string()
903    }
904
905    #[test]
906    fn payload_adds_the_rkyv_derives_and_redirects_the_crate() {
907        let out = expand(
908            quote! {},
909            quote! {
910                #[derive(Debug, Clone)]
911                pub struct Query {
912                    pub key: String,
913                }
914            },
915        )
916        .to_string();
917        assert!(
918            out.contains("ice_rpc :: codegen :: rkyv :: Archive"),
919            "{out}"
920        );
921        assert!(
922            out.contains("ice_rpc :: codegen :: rkyv :: Deserialize"),
923            "{out}"
924        );
925        assert!(
926            out.contains("ice_rpc :: codegen :: rkyv :: Serialize"),
927            "{out}"
928        );
929        assert!(
930            out.contains("rkyv (crate = ice_rpc :: codegen :: rkyv)"),
931            "{out}"
932        );
933        // The item's own derive and declaration are preserved.
934        assert!(out.contains("derive (Debug , Clone)"), "{out}");
935        assert!(out.contains("pub struct Query"), "{out}");
936    }
937
938    #[test]
939    fn payload_adds_debug_when_the_item_does_not_derive_it() {
940        let out = expand(
941            quote! {},
942            quote! {
943                pub struct Query { pub key: String }
944            },
945        );
946        // `monitoring` derives `Debug`, so an empty payload is still observable.
947        let generated = generated_derivation(&out);
948        assert!(generated.contains("Debug"), "{out}");
949    }
950
951    #[test]
952    fn payload_keeps_the_items_own_debug_derivation() {
953        let out = expand(
954            quote! {},
955            quote! {
956                #[derive(Debug, Clone)]
957                pub struct Query { pub key: String }
958            },
959        );
960        // Deriving it twice would be an `E0119`.
961        let generated = generated_derivation(&out);
962        assert!(!generated.contains("Debug"), "{out}");
963    }
964
965    #[test]
966    fn payload_detects_a_fully_qualified_debug_derive() {
967        let out = expand(
968            quote! {},
969            quote! {
970                #[derive(std::fmt::Debug)]
971                pub struct Query { pub key: String }
972            },
973        );
974        let generated = generated_derivation(&out);
975        assert!(!generated.contains("Debug"), "{out}");
976    }
977
978    #[test]
979    fn payload_no_debug_leaves_the_derivation_to_a_hand_written_impl() {
980        let out = expand(
981            quote! { no_debug },
982            quote! {
983                pub struct Point { pub x: i32 }
984            },
985        );
986        let generated = generated_derivation(&out);
987        assert!(!generated.contains("Debug"), "{out}");
988        assert!(
989            generated.contains("ice_rpc :: codegen :: rkyv :: Archive"),
990            "{out}"
991        );
992    }
993
994    #[test]
995    fn payload_display_delegates_to_debug() {
996        let out = expand(
997            quote! { display },
998            quote! {
999                pub enum MyError { NotFound }
1000            },
1001        );
1002        let rendered = out.to_string();
1003        // The trait `?` needs to reach a `Box<dyn Error>`, rendered by `Debug`.
1004        assert!(
1005            rendered.contains(
1006                "impl :: std :: fmt :: Display for MyError where MyError : :: std :: fmt :: Debug"
1007            ),
1008            "{rendered}"
1009        );
1010        assert!(
1011            rendered.contains(":: std :: fmt :: Debug :: fmt (self , f)"),
1012            "{rendered}"
1013        );
1014        // `Display` needs something to render, so `Debug` is still derived.
1015        assert!(generated_derivation(&out).contains("Debug"), "{rendered}");
1016    }
1017
1018    #[test]
1019    fn payload_display_on_a_generic_type_bounds_the_delegation() {
1020        let out = expand(
1021            quote! { display },
1022            quote! {
1023                pub struct Wrapper<T> { pub inner: T }
1024            },
1025        )
1026        .to_string();
1027        // The derived `Debug` carries the `T: Debug` bounds: state them.
1028        assert!(
1029            out.contains("where Wrapper < T > : :: std :: fmt :: Debug"),
1030            "{out}"
1031        );
1032    }
1033
1034    #[test]
1035    fn payload_refuses_display_combined_with_no_debug() {
1036        let out = expand(
1037            quote! { display, no_debug },
1038            quote! {
1039                pub struct Query { pub key: String }
1040            },
1041        )
1042        .to_string();
1043        assert!(
1044            out.contains("cannot combine `display` with `no_debug`"),
1045            "{out}"
1046        );
1047    }
1048
1049    #[test]
1050    fn payload_refuses_an_unknown_parameter() {
1051        let out = expand(
1052            quote! { debug },
1053            quote! {
1054                pub struct Query { pub key: String }
1055            },
1056        )
1057        .to_string();
1058        assert!(out.contains("unknown parameter `debug`"), "{out}");
1059    }
1060
1061    #[test]
1062    fn payload_works_on_an_enum() {
1063        let out = expand(
1064            quote! {},
1065            quote! {
1066                pub enum Status { Ok, Nok }
1067            },
1068        )
1069        .to_string();
1070        assert!(
1071            out.contains("ice_rpc :: codegen :: rkyv :: Archive"),
1072            "{out}"
1073        );
1074        assert!(out.contains("pub enum Status"), "{out}");
1075    }
1076
1077    #[test]
1078    fn payload_adds_serde_derives_when_the_json_block_is_on() {
1079        let out = expand_json(
1080            quote! {},
1081            quote! {
1082                pub struct Query { pub key: String }
1083            },
1084        )
1085        .to_string();
1086        assert!(
1087            out.contains("ice_rpc :: codegen :: serde :: Serialize"),
1088            "{out}"
1089        );
1090        assert!(
1091            out.contains("ice_rpc :: codegen :: serde :: Deserialize"),
1092            "{out}"
1093        );
1094        // Resolved through the re-export: no `serde` dependency in the service crate.
1095        assert!(
1096            out.contains(r#"serde (crate = "ice_rpc::codegen::serde")"#),
1097            "{out}"
1098        );
1099    }
1100
1101    #[test]
1102    fn payload_without_the_json_block_adds_no_serde() {
1103        let out = expand(
1104            quote! {},
1105            quote! {
1106                pub struct Query { pub key: String }
1107            },
1108        )
1109        .to_string();
1110        assert!(!out.contains("serde"), "{out}");
1111    }
1112
1113    /// A type that already derives the pair keeps its own — a second derivation
1114    /// would be an `E0119` — and its author keeps ownership of the container
1115    /// attributes.
1116    #[test]
1117    fn payload_keeps_a_serde_derivation_already_written() {
1118        let out = expand_json(
1119            quote! {},
1120            quote! {
1121                #[derive(serde::Serialize, serde::Deserialize)]
1122                pub struct Query { pub key: String }
1123            },
1124        )
1125        .to_string();
1126        // Nothing added: a second derivation would be an `E0119`.
1127        assert_eq!(out.matches("serde :: Serialize").count(), 1, "{out}");
1128        assert!(!out.contains("codegen :: serde :: Serialize"), "{out}");
1129        assert!(!out.contains("codegen :: serde :: Deserialize"), "{out}");
1130        assert!(!out.contains("serde (crate = "), "{out}");
1131    }
1132
1133    #[test]
1134    fn payload_no_serde_opts_out() {
1135        let out = expand_json(
1136            quote! { no_serde },
1137            quote! {
1138                pub struct Query { pub key: String }
1139            },
1140        )
1141        .to_string();
1142        assert!(!out.contains("serde"), "{out}");
1143    }
1144
1145    #[test]
1146    fn payload_refuses_a_non_struct_or_enum_item() {
1147        let out = expand(quote! {}, quote! { fn free() {} }).to_string();
1148        assert!(
1149            out.contains("may only be applied to a struct or an enum"),
1150            "{out}"
1151        );
1152    }
1153
1154    #[test]
1155    fn payload_refuses_an_item_that_already_sets_the_rkyv_crate() {
1156        let out = expand(
1157            quote! {},
1158            quote! {
1159                #[rkyv(crate = other::place)]
1160                pub struct Query { pub key: String }
1161            },
1162        )
1163        .to_string();
1164        assert!(out.contains("already sets"), "{out}");
1165    }
1166}
1167
1168#[cfg(test)]
1169mod entry_tests {
1170    use super::entry::expand_main;
1171    use proc_macro2::TokenStream;
1172    use quote::quote;
1173
1174    fn expand(attr: TokenStream, item: TokenStream) -> String {
1175        expand_main(attr, item)
1176            .expect("expansion should succeed")
1177            .to_string()
1178    }
1179
1180    #[test]
1181    fn main_default_uses_the_agnostic_driver() {
1182        let out = expand(
1183            quote! {},
1184            quote! { async fn main() -> Result<(), String> { Ok(()) } },
1185        );
1186        assert!(out.contains("ice_rpc :: rt :: block_on"), "{out}");
1187        assert!(out.contains("ice_rpc :: codegen :: init ()"), "{out}");
1188        assert!(out.contains("-> Result < () , String >"), "{out}");
1189        assert!(
1190            out.starts_with("fn main"),
1191            "the generated main must be sync: {out}"
1192        );
1193        assert!(!out.contains("async fn main"), "{out}");
1194    }
1195
1196    #[test]
1197    fn main_tokio_builds_a_tokio_runtime() {
1198        let out = expand(quote! { tokio }, quote! { async fn main() {} });
1199        assert!(out.contains("new_multi_thread"), "{out}");
1200        assert!(!out.contains("ice_rpc :: rt :: block_on"), "{out}");
1201    }
1202
1203    #[test]
1204    fn main_custom_driver_is_used_verbatim() {
1205        let out = expand(quote! { smol::block_on }, quote! { async fn main() {} });
1206        assert!(out.contains("smol :: block_on"), "{out}");
1207    }
1208
1209    #[test]
1210    fn main_wraps_body_in_an_inner_async_block() {
1211        let out = expand(quote! {}, quote! { async fn main() {} });
1212        // After the awaited body, so an early `return` cannot skip it.
1213        let shutdown = out.find("shutdown").expect("shutdown() missing");
1214        let body_await = out.find(". await").expect("body await missing");
1215        assert!(body_await < shutdown, "{out}");
1216    }
1217
1218    #[test]
1219    fn main_rejects_a_synchronous_function() {
1220        let err = expand_main(quote! {}, quote! { fn main() {} }).unwrap_err();
1221        assert!(err.to_string().contains("async fn main"));
1222    }
1223
1224    #[test]
1225    fn main_rt_none_wraps_a_synchronous_main() {
1226        let out = expand(quote! { rt-none }, quote! { fn main() {} });
1227        assert!(out.contains("ice_rpc :: codegen :: init ()"), "{out}");
1228        assert!(out.contains("shutdown_blocking"), "{out}");
1229        assert!(out.starts_with("fn main"), "{out}");
1230        // No runtime, no future: nothing `async`, nothing `block_on`.
1231        assert!(!out.contains("async"), "{out}");
1232        assert!(!out.contains("block_on"), "{out}");
1233    }
1234
1235    #[test]
1236    fn main_rt_none_rejects_an_async_function() {
1237        let err = expand_main(quote! { rt-none }, quote! { async fn main() {} }).unwrap_err();
1238        assert!(err.to_string().contains("synchronous"), "{err}");
1239    }
1240}
1241
1242#[cfg(test)]
1243mod trait_requirements_tests {
1244    use super::inject_trait_requirements;
1245    use syn::ItemTrait;
1246
1247    #[test]
1248    fn a_bare_trait_gets_the_attribute_and_the_three_bounds() {
1249        let mut item: ItemTrait = syn::parse_quote! { trait Bare {} };
1250        inject_trait_requirements(&mut item);
1251        assert_eq!(item.attrs.len(), 1);
1252        assert_eq!(item.supertraits.len(), 3);
1253    }
1254
1255    #[test]
1256    fn a_trait_that_already_declares_them_keeps_one_copy() {
1257        let mut item: ItemTrait = syn::parse_quote! {
1258            #[async_trait::async_trait]
1259            trait Declared: Send + Sync + 'static {}
1260        };
1261        inject_trait_requirements(&mut item);
1262        // `syn` nodes have no `Debug` without `extra-traits`: show the tokens.
1263        let rendered = quote::quote!(#item).to_string();
1264        assert_eq!(
1265            item.attrs.len(),
1266            1,
1267            "the attribute must not be duplicated: {rendered}"
1268        );
1269        assert_eq!(
1270            item.supertraits.len(),
1271            3,
1272            "the bounds must not be duplicated: {rendered}"
1273        );
1274    }
1275
1276    #[test]
1277    fn a_partially_declared_trait_is_completed_in_order() {
1278        let mut item: ItemTrait = syn::parse_quote! { trait Partial: Send {} };
1279        inject_trait_requirements(&mut item);
1280        let rendered = quote::quote!(#item).to_string();
1281        assert!(
1282            rendered.contains("Send + Sync + 'static"),
1283            "the missing bounds must be appended after the declared one: {rendered}"
1284        );
1285    }
1286}