Skip to main content

repe_derive/
lib.rs

1//! Procedural macros for the `repe` crate.
2//!
3//! Two entry points, both of which exist so the served RPC surface is derived
4//! from the type rather than restated next to it:
5//!
6//! * [`macro@RepeStruct`] — a derive that reflects a struct's **fields** into
7//!   JSON Pointer endpoints.
8//! * [`macro@methods`] — an attribute on an inherent `impl` block that reflects
9//!   its **methods**. A derive macro cannot see `impl` blocks, so this is a
10//!   separate macro tied to the derive by a compile-time handshake.
11
12use proc_macro::TokenStream;
13use proc_macro_crate::{FoundCrate, crate_name};
14use proc_macro2::{Span, TokenStream as TokenStream2};
15use quote::{ToTokens, format_ident, quote, quote_spanned};
16use syn::{
17    Attribute, DeriveInput, Field, FnArg, GenericArgument, Ident, ImplItem, ItemImpl, LitStr,
18    PathArguments, ReturnType, Signature, Token, Type,
19    meta::ParseNestedMeta,
20    parse::{Parse, ParseBuffer, ParseStream},
21    parse_macro_input,
22    punctuated::Punctuated,
23    spanned::Spanned,
24};
25
26#[proc_macro_derive(RepeStruct, attributes(repe))]
27pub fn derive_repe_struct(input: TokenStream) -> TokenStream {
28    let input = parse_macro_input!(input as DeriveInput);
29    match expand_repe_struct(&input) {
30        Ok(tokens) => tokens.into(),
31        Err(err) => err.to_compile_error().into(),
32    }
33}
34
35/// Publish every method of an inherent `impl` block as an RPC endpoint.
36///
37/// See `repe::structs::RepeMethods` for the shape; the struct must carry the
38/// `#[repe(methods)]` marker beside its `#[derive(RepeStruct)]` so the derived
39/// router dispatches here.
40#[proc_macro_attribute]
41pub fn methods(attr: TokenStream, item: TokenStream) -> TokenStream {
42    if !attr.is_empty() {
43        let attr: TokenStream2 = attr.into();
44        return syn::Error::new_spanned(attr, "`#[repe::methods]` takes no arguments")
45            .to_compile_error()
46            .into();
47    }
48    let item_impl = parse_macro_input!(item as ItemImpl);
49    expand_methods(item_impl).into()
50}
51
52// ---------------------------------------------------------------------------
53// Response emitters — how a generated arm answers
54// ---------------------------------------------------------------------------
55//
56// These were methods on a `Sink` enum, because `RepeStruct` used to carry two
57// dispatch methods that had to agree: `repe_handle` returned an owned
58// `serde_json::Value` and `repe_handle_into` encoded straight into the response
59// body, and generating both from one `Sink`-parameterised builder is what kept
60// them in lockstep. There is one dispatch method now — the `Value` form went
61// with `serde_json::Value` — so the parameter, and the whole class of bug it
62// guarded against, is gone.
63
64/// Respond with nothing: the acknowledgement for a write, or a method returning
65/// `()`.
66fn emit_null() -> TokenStream2 {
67    quote! {
68        {
69            out.write_null();
70            Ok(())
71        }
72    }
73}
74
75/// Respond with `expr`, serialized as JSON.
76///
77/// Deliberately an expression of type `StructResult<()>` rather than
78/// `{ write(..)?; Ok(()) }`. That is what makes it usable where `?` is not,
79/// which is how the shared-borrow read path reuses these emitters verbatim
80/// under its `Option` return instead of keeping a second copy of them.
81///
82/// No error path and no endpoint literal: a `structio::json::Write` impl
83/// returns `()`, so writing a response cannot fail.
84fn emit_value(expr: TokenStream2) -> TokenStream2 {
85    emit_value_spanned(Span::call_site(), expr)
86}
87
88/// [`emit_value`] with the span a bound failure should point at.
89///
90/// structio's bounds are what a user trips here — a field whose type has no
91/// `object!` declaration — and the token worth underlining is the field, not the
92/// derive that happened to visit it. Same reasoning as the `quote_spanned!` on
93/// a method invocation below, with more force: a field's type is written down
94/// right there.
95fn emit_value_spanned(span: Span, expr: TokenStream2) -> TokenStream2 {
96    quote_spanned! {span=>
97        {
98            out.write(&#expr);
99            Ok(())
100        }
101    }
102}
103
104/// Respond with `expr` as a BEVE typed numeric array.
105///
106/// Inside an enclosing object the body falls back to a JSON array, which
107/// `ResponseBody` decides for itself — see its `nested` flag.
108fn emit_typed_slice(expr: TokenStream2) -> TokenStream2 {
109    emit_typed_slice_spanned(Span::call_site(), expr)
110}
111
112/// [`emit_typed_slice`] with the span a bound failure should point at. See
113/// [`emit_value_spanned`].
114fn emit_typed_slice_spanned(span: Span, expr: TokenStream2) -> TokenStream2 {
115    quote_spanned! {span=>
116        {
117            out.write_typed_slice(&#expr[..]);
118            Ok(())
119        }
120    }
121}
122
123// ---------------------------------------------------------------------------
124// #[derive(RepeStruct)]
125// ---------------------------------------------------------------------------
126
127fn expand_repe_struct(input: &DeriveInput) -> syn::Result<TokenStream2> {
128    let repe = repe_crate_path();
129
130    let struct_ident = &input.ident;
131    let syn::Data::Struct(data_struct) = &input.data else {
132        return Err(syn::Error::new_spanned(
133            input,
134            "RepeStruct can only be derived for structs",
135        ));
136    };
137
138    let fields = match &data_struct.fields {
139        syn::Fields::Named(named) => &named.named,
140        _ => {
141            return Err(syn::Error::new_spanned(
142                &input.ident,
143                "RepeStruct requires named fields",
144            ));
145        }
146    };
147
148    let struct_attrs = parse_struct_attrs(&input.attrs)?;
149    let field_specs = fields
150        .iter()
151        .map(parse_field)
152        .collect::<syn::Result<Vec<_>>>()?;
153
154    // An endpoint that two declarations claim is not a warning-level problem:
155    // one of them silently becomes unreachable, and the listing emits a
156    // duplicate JSON key. Reject every collision the macro can see.
157    let mut endpoints: Vec<(&str, Span)> = Vec::new();
158    for field in &field_specs {
159        if !field.attrs.skip {
160            endpoints.push((&field.endpoint, field.ident.span()));
161        }
162    }
163    for method in &struct_attrs.methods {
164        endpoints.push((&method.endpoint, method.method_ident.span()));
165    }
166    reject_duplicate_endpoints(&endpoints)?;
167
168    let from_impl_block = struct_attrs.methods_from_impl_block;
169
170    if let Some(order) = &struct_attrs.listing_order {
171        validate_listing_order(order, &endpoints, from_impl_block)?;
172    }
173    let entries = listing_entries(
174        &field_specs,
175        &struct_attrs.methods,
176        from_impl_block,
177        struct_attrs.listing_order.as_ref(),
178    );
179
180    // The compile-time handshake, both directions. `MethodsDeclared` is a
181    // supertrait of `RepeMethods`, so a `#[repe::methods]` block without this
182    // marker cannot compile; and the fallthrough below names `RepeMethods`, so
183    // this marker without a block cannot either.
184    let handshake = from_impl_block.then(|| {
185        // Everything the *derive* publishes: fields, plus any method named in a
186        // struct-level `#[repe(methods(..))]` list. Both win dispatch over the
187        // impl block's table, so both have to be in the cross-macro check —
188        // leaving the listed methods out is how a struct-list method and an
189        // impl-block accessor of the same name once compiled clean and emitted
190        // the key twice.
191        let declared: Vec<LitStr> = endpoints
192            .iter()
193            .map(|(endpoint, _)| LitStr::new(endpoint, Span::call_site()))
194            .collect();
195        // The other half of `validate_listing_order`. The derive rejects every
196        // mistake it can name; the impl block's endpoints are not among them,
197        // and the two generated tables are the only place they are visible.
198        let order_check = struct_attrs.listing_order.as_ref().map(|order| {
199            let keys = &order.keys;
200            // A const-eval failure is reported at the span of the *call
201            // expression*, which is the span of its leading token — and that
202            // token is the crate path, emitted at call site. Without respanning
203            // it, an order that omits an impl-block endpoint would point at
204            // `#[derive(RepeStruct)]` rather than at the attribute that named
205            // the wrong set.
206            let assert = respan(quote! { #repe::structs::assert_listing_order }, order.span);
207            quote_spanned! { order.span=>
208                const _: () = #assert(
209                    &[#(#keys),*],
210                    &[#(#declared),*],
211                    <#struct_ident as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES,
212                    <#struct_ident as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS,
213                    <#struct_ident as #repe::structs::RepeMethods>::REPE_TABLE_RECOVERED,
214                );
215            }
216        });
217        quote! {
218            impl #repe::structs::MethodsDeclared for #struct_ident {}
219
220            // The cross-macro half of the collision check: neither macro sees
221            // the other's endpoint names, but the generated consts do.
222            const _: () = #repe::structs::assert_no_endpoint_collision(
223                &[#(#declared),*],
224                <#struct_ident as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES,
225                <#struct_ident as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS,
226            );
227
228            #order_check
229        }
230    });
231
232    // The same terms the listing's guard is built from, published so a parent
233    // that nests this struct can settle its listing before writing anything.
234    // Empty means the constant `false`, which is a plain struct of leaf fields —
235    // the common case, which then carries no guard at all.
236    let decline_terms = listing_decline_terms(&field_specs, from_impl_block, &repe);
237    let listing_declines = if decline_terms.is_empty() {
238        quote! { false }
239    } else {
240        quote! { #(#decline_terms)||* }
241    };
242
243    // Whether the router should bother with the shared attempt for a frame that
244    // carries a body. Empty means the constant `false`: every write here needs
245    // the exclusive borrow, so the read lock, the walk and the decline are all
246    // work whose outcome is known before it starts.
247    let body_terms = shared_body_terms(&field_specs, &struct_attrs, from_impl_block, &repe);
248    let shared_serves_bodies = if body_terms.is_empty() {
249        quote! { false }
250    } else {
251        quote! { #(#body_terms)||* }
252    };
253
254    let mut bodies = Vec::new();
255    {
256        let listing = build_listing(&entries, &repe, Borrow::Exclusive);
257        let field_arms = build_field_arms(&field_specs, &repe, Borrow::Exclusive);
258        let method_arms = build_method_arms(&struct_attrs.methods, &repe, Borrow::Exclusive);
259        let fallthrough = if from_impl_block {
260            quote! {
261                _ => <Self as #repe::structs::RepeMethods>::repe_call_into(
262                    self, segments, body, out,
263                ),
264            }
265        } else {
266            quote! {
267                _ => Err(#repe::StructError::InvalidPath {
268                    path: #repe::structs::path_from_segments(segments),
269                }),
270            }
271        };
272        // The whole-object write. `#[repe(readonly)]` on the struct emits *only*
273        // the refusal — never the assignment followed by dead code — which is
274        // the point beyond the refusal itself: the read into `*self` is then
275        // never generated, so the struct is not required to be readable at all.
276        // A type holding live handles has no body that produces one.
277        let root_write = if struct_attrs.no_replace {
278            quote! {
279                if body.is_some() {
280                    return Err(#repe::StructError::BodyUnexpected {
281                        path: String::from(""),
282                    });
283                }
284            }
285        } else {
286            let root_write_ack = emit_null();
287            quote! {
288                if let Some(__repe_body) = body {
289                    __repe_body.read_into("", self)?;
290                    return #root_write_ack;
291                }
292            }
293        };
294
295        bodies.push(quote! {
296            fn repe_handle_into(
297                &mut self,
298                segments: &[&str],
299                body: Option<#repe::structs::RequestBody<'_>>,
300                out: &mut #repe::structs::ResponseBody<'_>,
301            ) -> #repe::structs::StructResult<()> {
302                if segments.is_empty() {
303                    #root_write
304                    return #listing;
305                }
306
307                let (head, tail) = segments.split_first().unwrap();
308                match *head {
309                    #(#field_arms)*
310                    #(#method_arms)*
311                    #fallthrough
312                }
313            }
314        });
315    }
316
317    // Settled before the shared listing writes or calls anything, and for the
318    // whole subtree — see `listing_decline_terms`. Past it no entry can decline,
319    // so the `entry_try_with` rewinds inside are the safety net for a
320    // hand-written table that got the guard's inputs wrong, not a path a derived
321    // listing takes. Every term folds to a constant, and a struct with none gets
322    // no guard emitted.
323    let shared_listing = {
324        let listing = build_listing(&entries, &repe, Borrow::Shared);
325        let guard = (!decline_terms.is_empty()).then(|| {
326            quote! {
327                if <Self as #repe::RepeStruct>::repe_listing_declines(self) {
328                    return None;
329                }
330            }
331        });
332        quote! {
333            {
334                #guard
335                #listing
336            }
337        }
338    };
339    let shared_field_arms = build_field_arms(&field_specs, &repe, Borrow::Shared);
340    let shared_method_arms = build_method_arms(&struct_attrs.methods, &repe, Borrow::Shared);
341    let shared_fallthrough = if from_impl_block {
342        quote! {
343            _ => <Self as #repe::structs::RepeMethods>::repe_call_shared_into(
344                self, segments, body, out,
345            ),
346        }
347    } else {
348        quote! {
349            _ => Some(Err(#repe::StructError::InvalidPath {
350                path: #repe::structs::path_from_segments(segments),
351            })),
352        }
353    };
354    // A whole-object write needs `&mut self`, so it declines — unless the struct
355    // is read-only, where the refusal itself is servable and there is no reason
356    // to take the exclusive lock to give it.
357    let shared_root_write = if struct_attrs.no_replace {
358        quote! {
359            if body.is_some() {
360                return Some(Err(#repe::StructError::BodyUnexpected {
361                    path: String::from(""),
362                }));
363            }
364        }
365    } else {
366        quote! {
367            if body.is_some() {
368                return None;
369            }
370        }
371    };
372    bodies.push(quote! {
373        fn repe_listing_declines(&self) -> bool {
374            #listing_declines
375        }
376    });
377
378    bodies.push(quote! {
379        const REPE_SHARED_SERVES_BODIES: bool = #shared_serves_bodies;
380    });
381
382    bodies.push(quote! {
383        fn repe_shared_into(
384            &self,
385            segments: &[&str],
386            body: Option<#repe::structs::RequestBody<'_>>,
387            out: &mut #repe::structs::ResponseBody<'_>,
388        ) -> Option<#repe::structs::StructResult<()>> {
389            if segments.is_empty() {
390                #shared_root_write
391                return #shared_listing;
392            }
393
394            let (head, tail) = segments.split_first().unwrap();
395            match *head {
396                #(#shared_field_arms)*
397                #(#shared_method_arms)*
398                #shared_fallthrough
399            }
400        }
401    });
402
403    Ok(quote! {
404        impl #repe::RepeStruct for #struct_ident {
405            #(#bodies)*
406        }
407
408        #handshake
409    })
410}
411
412/// Re-span every token of `tokens`, which here is always a path: a shallow walk
413/// covers it because a path carries no delimited groups.
414fn respan(tokens: TokenStream2, span: Span) -> TokenStream2 {
415    tokens
416        .into_iter()
417        .map(|mut tree| {
418            tree.set_span(span);
419            tree
420        })
421        .collect()
422}
423
424/// The crate root the generated paths hang off: `::repe`, or `::repe_core` for a
425/// crate that has only the core.
426///
427/// The `RepeStruct` surface lives in `repe-core` and is re-exported by `repe` at
428/// the same paths, so either name is a valid root and one macro serves both. A
429/// crate that has both wants the one it actually calls, which is why `repe` is
430/// tried first.
431///
432/// Always an absolute path, never `crate`, even when expanding inside one of the
433/// two crates. `proc_macro_crate` reports `Itself` for every target that is not
434/// an integration test (it detects those by `CARGO_TARGET_TMPDIR`), which lumps
435/// a crate's own examples and doc-tests in with its lib — and in those `crate`
436/// is the example, not the library. An `extern crate self as ..;` in each
437/// `lib.rs` makes the absolute path resolve from inside the lib too, so one
438/// spelling is correct for all four cases.
439fn repe_crate_path() -> TokenStream2 {
440    for (package, itself) in [("repe", "repe"), ("repe-core", "repe_core")] {
441        let name = match crate_name(package) {
442            Ok(FoundCrate::Itself) => String::from(itself),
443            Ok(FoundCrate::Name(name)) => name,
444            // Not a dependency of the crate being expanded. Try the other.
445            Err(_) => continue,
446        };
447        let ident = Ident::new(&name, Span::call_site());
448        return quote!(::#ident);
449    }
450    // Neither resolved — no manifest to read, most likely. `repe` is the name
451    // the overwhelming majority of callers depend on.
452    quote!(::repe)
453}
454
455/// Reject two declarations claiming the same endpoint, pointing at the second.
456fn reject_duplicate_endpoints(endpoints: &[(&str, Span)]) -> syn::Result<()> {
457    for (index, (name, _)) in endpoints.iter().enumerate() {
458        if endpoints[..index].iter().any(|(prior, _)| prior == name) {
459            return Err(syn::Error::new(
460                endpoints[index].1,
461                format!(
462                    "endpoint `{name}` is declared twice on this struct; one of them would be \
463                     unreachable and the whole-struct listing would emit the key twice. Rename \
464                     one with `#[repe(rename = \"...\")]`."
465                ),
466            ));
467        }
468    }
469    Ok(())
470}
471
472// ---------------------------------------------------------------------------
473// Attributes
474// ---------------------------------------------------------------------------
475
476#[derive(Default)]
477struct FieldAttrs {
478    rename: Option<String>,
479    skip: bool,
480    nested: bool,
481    readonly: bool,
482    typed: bool,
483}
484
485struct FieldSpec {
486    ident: Ident,
487    ty: Type,
488    attrs: FieldAttrs,
489    endpoint: String,
490}
491
492/// Parse the `skip` / `rename = "..."` pair shared by field and method
493/// attributes. `Ok(false)` means the meta was not one of these, so the caller
494/// should keep looking.
495fn parse_shared_meta(
496    meta: &ParseNestedMeta<'_>,
497    rename: &mut Option<String>,
498    skip: &mut bool,
499) -> syn::Result<bool> {
500    if meta.path.is_ident("skip") {
501        *skip = true;
502        return Ok(true);
503    }
504    if meta.path.is_ident("rename") {
505        let lit: LitStr = meta.value()?.parse()?;
506        *rename = Some(lit.value());
507        return Ok(true);
508    }
509    Ok(false)
510}
511
512fn parse_field(field: &Field) -> syn::Result<FieldSpec> {
513    let ident = field
514        .ident
515        .clone()
516        .ok_or_else(|| syn::Error::new(field.span(), "expected named field"))?;
517    let mut attrs = FieldAttrs::default();
518
519    for attr in &field.attrs {
520        if !attr.path().is_ident("repe") {
521            continue;
522        }
523        attr.parse_nested_meta(|meta| {
524            if parse_shared_meta(&meta, &mut attrs.rename, &mut attrs.skip)? {
525                return Ok(());
526            }
527            if meta.path.is_ident("nested") {
528                attrs.nested = true;
529                return Ok(());
530            }
531            if meta.path.is_ident("nested_serde") {
532                return Err(meta.error(
533                    "`#[repe(nested_serde)]` is gone: it descended into a field by walking a \
534                     `serde_json::Value` of it, and there is no tree to walk. Use \
535                     `#[repe(nested)]` where the child can implement `RepeStruct`, and a \
536                     structio adapter (`json::ReadAs` / `WriteAs`, named at the field as \
537                     `field as Adapter`) for a type whose crate cannot depend on this one.",
538                ));
539            }
540            if meta.path.is_ident("readonly") {
541                attrs.readonly = true;
542                return Ok(());
543            }
544            if meta.path.is_ident("typed") {
545                attrs.typed = true;
546                return Ok(());
547            }
548            Err(meta.error("unsupported `repe` field attribute"))
549        })?;
550    }
551
552    if attrs.typed && attrs.nested {
553        return Err(syn::Error::new(
554            field.span(),
555            "`#[repe(typed)]` encodes a numeric slice as a BEVE typed array, which a nested struct is not",
556        ));
557    }
558
559    let endpoint = attrs.rename.clone().unwrap_or_else(|| ident.to_string());
560
561    Ok(FieldSpec {
562        ident,
563        ty: field.ty.clone(),
564        attrs,
565        endpoint,
566    })
567}
568
569#[derive(Debug, Clone, Copy)]
570enum ReceiverKind {
571    Ref,
572    Mut,
573}
574
575/// What a published method returns, and how that maps onto the wire.
576struct ReturnSpec {
577    /// The `Ok` payload type — `()` when there is nothing to send.
578    ok_ty: Type,
579    /// Whether the declared return type is a `Result`, in which case `Err`
580    /// becomes an error frame rather than part of the payload.
581    fallible: bool,
582    /// The declared return type, verbatim, for the published signature string.
583    display: String,
584}
585
586impl ReturnSpec {
587    fn ok_is_unit(&self) -> bool {
588        matches!(&self.ok_ty, Type::Tuple(tuple) if tuple.elems.is_empty())
589    }
590}
591
592struct MethodSpec {
593    endpoint: String,
594    method_ident: Ident,
595    /// `&self` or `&mut self`. Read by the shared-borrow path, which can only
596    /// call the former.
597    receiver: ReceiverKind,
598    args: Vec<(Ident, Type)>,
599    ret: ReturnSpec,
600    signature_display: String,
601}
602
603struct StructAttrs {
604    methods: Vec<MethodSpec>,
605    /// `#[repe(methods)]` with no list: the method table comes from a
606    /// `#[repe::methods]` impl block.
607    methods_from_impl_block: bool,
608    /// Struct-level `#[repe(readonly)]`: a write of the *whole* object is
609    /// refused rather than deserialized into `Self`.
610    ///
611    /// The point is not only the refusal — it is that the whole-object read is
612    /// then never emitted, so the struct is not required to be readable at all.
613    /// A type holding an open socket or a file handle has no body that produces
614    /// one, and declaring a reader that always errors trades a compile error for
615    /// a runtime one and is boilerplate on every such type. It emits only the
616    /// rejection, and never the assignment
617    /// followed by dead code, because a crate under `#![deny(warnings)]` must
618    /// not be broken by `unreachable_code` on generated code.
619    ///
620    /// Named for the operation it refuses rather than `readonly`, because the
621    /// two are different statements: `readonly` on a field says *this subtree is
622    /// not writable*, recursively, while this says *this type cannot be rebuilt
623    /// from a body* and leaves every field writable. One word for both would
624    /// read as correct and mean the wrong thing one level up, and it would
625    /// spend the spelling that the recursive meaning should have if a struct
626    /// ever wants it. `#[repe(readonly)]` on a struct is rejected outright,
627    /// pointing here.
628    no_replace: bool,
629    /// `#[repe(listing_order("a", "b", ..))]`: the key order of the
630    /// whole-object listing, given in full.
631    ///
632    /// Without it the listing appends in a fixed order — fields in declaration
633    /// order, then struct-listed methods, then the impl block's signatures, then
634    /// its field-shaped accessors — so a `#[repe(get/set)]` endpoint is always
635    /// last however its logical place reads. That is wire-visible, and it is the
636    /// one key order a `glz::object` with a `custom<setter, getter>` in the
637    /// middle cannot be reproduced in.
638    ///
639    /// Reorders emission only: it costs nothing at run time, and nothing at all
640    /// for a struct that does not use it.
641    ///
642    /// Governs both listings, which are the two that reach a client:
643    /// `repe_handle_into` and `repe_shared_into`. There is no third form to fall
644    /// out of step — the `serde_json::Map`-backed one, which sorted its keys and
645    /// so could carry no order at all, went with `serde_json::Value`.
646    listing_order: Option<ListingOrder>,
647}
648
649/// The parsed `#[repe(listing_order(..))]` list, with the span of the attribute
650/// that carried it for the errors raised against it.
651struct ListingOrder {
652    keys: Vec<LitStr>,
653    span: Span,
654}
655
656fn parse_struct_attrs(attrs: &[Attribute]) -> syn::Result<StructAttrs> {
657    let mut methods = Vec::new();
658    let mut methods_from_impl_block = false;
659    let mut no_replace = false;
660    let mut listing_order: Option<ListingOrder> = None;
661    for attr in attrs {
662        if !attr.path().is_ident("repe") {
663            continue;
664        }
665        attr.parse_nested_meta(|meta| {
666            if meta.path.is_ident("no_replace") {
667                no_replace = true;
668                return Ok(());
669            }
670            if meta.path.is_ident("readonly") {
671                // Deliberately an error rather than an alias. On a field
672                // `readonly` is recursive — it refuses every write *through*
673                // the field — and letting the same word mean "refuses only the
674                // whole-object write" one level up is a trap that reads as
675                // correct. The recursive meaning has no spelling on a struct
676                // today; leaving the word unclaimed is what keeps it available
677                // for one.
678                return Err(meta.error(
679                    "`#[repe(readonly)]` is a field attribute, and on a field it is recursive: \
680                     it refuses every write through the field. A struct wanting that marks its \
681                     fields. To refuse a write of the *whole* object while its fields stay \
682                     writable — which also drops the requirement that `Self` be readable at \
683                     all, for a type no body describes — use `#[repe(no_replace)]`.",
684                ));
685            }
686            if meta.path.is_ident("listing_order") {
687                let span = meta.path.span();
688                if listing_order.is_some() {
689                    return Err(meta.error(
690                        "`#[repe(listing_order(..))]` is given once and names every key; two \
691                         lists cannot both be the order",
692                    ));
693                }
694                let content;
695                syn::parenthesized!(content in meta.input);
696                let keys: Punctuated<LitStr, Token![,]> =
697                    content.parse_terminated(<LitStr as Parse>::parse, Token![,])?;
698                listing_order = Some(ListingOrder {
699                    keys: keys.into_iter().collect(),
700                    span,
701                });
702                return Ok(());
703            }
704            if meta.path.is_ident("methods") {
705                if !meta.input.peek(syn::token::Paren) {
706                    // Bare `#[repe(methods)]`: defer to the `#[repe::methods]`
707                    // impl block, which is the only place a full signature list
708                    // can be read off the source of truth.
709                    methods_from_impl_block = true;
710                    return Ok(());
711                }
712                let content;
713                syn::parenthesized!(content in meta.input);
714                let list: Punctuated<MethodSpec, Token![,]> =
715                    content.parse_terminated(MethodSpec::parse, Token![,])?;
716                methods.extend(list);
717                Ok(())
718            } else {
719                Err(meta.error("unsupported `repe` attribute"))
720            }
721        })?;
722    }
723    Ok(StructAttrs {
724        methods,
725        methods_from_impl_block,
726        no_replace,
727        listing_order,
728    })
729}
730
731impl Parse for MethodSpec {
732    fn parse(input: ParseStream) -> syn::Result<Self> {
733        let lookahead: Ident = input.parse()?;
734        let (endpoint, method_ident) = if input.peek(Token![=]) {
735            input.parse::<Token![=]>()?;
736            let method: Ident = input.parse()?;
737            (lookahead.to_string(), method)
738        } else {
739            let method = lookahead.clone();
740            (lookahead.to_string(), method)
741        };
742
743        let content;
744        syn::parenthesized!(content in input);
745        let receiver = parse_receiver(&content)?;
746
747        let mut args = Vec::new();
748        while content.peek(Token![,]) {
749            content.parse::<Token![,]>()?;
750            if content.is_empty() {
751                break;
752            }
753            let arg_ident: Ident = content.parse()?;
754            content.parse::<Token![:]>()?;
755            let arg_ty: Type = content.parse()?;
756            args.push((arg_ident, arg_ty));
757        }
758        if !content.is_empty() {
759            return Err(content.error("unexpected tokens in method parameter list"));
760        }
761
762        let ret_ty: Type = if input.peek(Token![->]) {
763            input.parse::<Token![->]>()?;
764            input.parse::<Type>()?
765        } else {
766            syn::parse_quote! { () }
767        };
768        let ret = classify_return(&ret_ty);
769        let signature_display = build_signature_string(receiver, &args, &ret);
770
771        Ok(MethodSpec {
772            endpoint,
773            method_ident,
774            receiver,
775            args,
776            ret,
777            signature_display,
778        })
779    }
780}
781
782fn parse_receiver(input: &ParseBuffer<'_>) -> syn::Result<ReceiverKind> {
783    input.parse::<Token![&]>()?;
784    if input.peek(Token![mut]) {
785        input.parse::<Token![mut]>()?;
786        input.parse::<Token![self]>()?;
787        Ok(ReceiverKind::Mut)
788    } else {
789        input.parse::<Token![self]>()?;
790        Ok(ReceiverKind::Ref)
791    }
792}
793
794/// Recognize a `Result` return so `Err` becomes an error frame.
795///
796/// The check is **name-based**: the macro sees a type, not a resolved one, so it
797/// matches anything whose last path segment is `Result` with one or two type
798/// arguments. That covers `Result<T, E>`, `std::result::Result<T, E>`, and the
799/// widespread one-parameter aliases (`anyhow::Result<T>`, `std::io::Result<T>`,
800/// a crate's own `pub type Result<T> = ...`).
801///
802/// It misses a `Result` aliased under another name (`type DeviceResult<T> = ...`),
803/// which is then serialized as data — `Err` reaching the client as a *success*
804/// frame carrying `{"Err": ...}`. It also misreads a type of your own that is
805/// named `Result` but is not one. Both directions are documented; resolving them
806/// would need type information a macro does not have.
807fn classify_return(ty: &Type) -> ReturnSpec {
808    let display = normalize_type_string(ty);
809    if let Type::Path(type_path) = ty
810        && type_path.qself.is_none()
811        && let Some(segment) = type_path.path.segments.last()
812        && segment.ident == "Result"
813        && let PathArguments::AngleBracketed(generics) = &segment.arguments
814    {
815        let type_args: Vec<&Type> = generics
816            .args
817            .iter()
818            .filter_map(|arg| match arg {
819                GenericArgument::Type(ty) => Some(ty),
820                _ => None,
821            })
822            .collect();
823        if matches!(type_args.len(), 1 | 2) {
824            return ReturnSpec {
825                ok_ty: type_args[0].clone(),
826                fallible: true,
827                display,
828            };
829        }
830    }
831    ReturnSpec {
832        ok_ty: ty.clone(),
833        fallible: false,
834        display,
835    }
836}
837
838fn build_signature_string(
839    receiver: ReceiverKind,
840    args: &[(Ident, Type)],
841    ret: &ReturnSpec,
842) -> String {
843    let recv = match receiver {
844        ReceiverKind::Ref => "&self",
845        ReceiverKind::Mut => "&mut self",
846    };
847    let mut params = String::from(recv);
848    for (name, ty) in args {
849        params.push_str(", ");
850        params.push_str(&name.to_string());
851        params.push_str(": ");
852        params.push_str(&normalize_type_string(ty));
853    }
854    format!("fn({}) -> {}", params, ret.display)
855}
856
857fn normalize_type_string(ty: &Type) -> String {
858    ty.to_token_stream()
859        .to_string()
860        .replace(" ,", ",")
861        .replace(" :: ", "::")
862        .replace(" < ", "<")
863        .replace(" >", ">")
864        .replace("& '", "&'")
865}
866
867// ---------------------------------------------------------------------------
868// Whole-struct listing
869// ---------------------------------------------------------------------------
870
871/// One key of the whole-object listing.
872///
873/// Resolved either from declaration order — fields, then struct-listed methods,
874/// then the impl block's two tables — or from `#[repe(listing_order(..))]`,
875/// which names the whole sequence. Both listings walk this one list, so they
876/// cannot disagree about what is emitted or in what order.
877enum ListingEntry<'a> {
878    /// A field, listed by its value.
879    Field(&'a FieldSpec),
880    /// A struct-level `#[repe(methods(..))]` entry, listed by its signature
881    /// string.
882    Signature(&'a MethodSpec),
883    /// One endpoint of the `#[repe::methods]` impl block, placed by name. Which
884    /// of the block's two tables it came from is resolved in a `const` block,
885    /// since this macro cannot see the block itself.
886    ImplNamed(LitStr),
887    /// Every `REPE_METHOD_SIGNATURES` entry, in table order. Emitted only when
888    /// there is no `listing_order` placing them individually.
889    ImplSignatures,
890    /// Every `REPE_ACCESSOR_ENDPOINTS` entry, in table order. Same condition.
891    ImplAccessors,
892}
893
894/// Resolve the listing's keys, in the order they will be emitted.
895fn listing_entries<'a>(
896    fields: &'a [FieldSpec],
897    methods: &'a [MethodSpec],
898    from_impl_block: bool,
899    order: Option<&ListingOrder>,
900) -> Vec<ListingEntry<'a>> {
901    let Some(order) = order else {
902        let mut entries: Vec<ListingEntry<'a>> = fields
903            .iter()
904            .filter(|field| !field.attrs.skip)
905            .map(ListingEntry::Field)
906            .collect();
907        entries.extend(methods.iter().map(ListingEntry::Signature));
908        if from_impl_block {
909            entries.push(ListingEntry::ImplSignatures);
910            entries.push(ListingEntry::ImplAccessors);
911        }
912        return entries;
913    };
914
915    // Every name here has been checked: against the fields and listed methods at
916    // macro time, and against the impl block's tables by the `const` assertion
917    // the handshake emits. So a name this macro does not recognize is an impl
918    // block endpoint, not a typo.
919    order
920        .keys
921        .iter()
922        .map(|key| {
923            let name = key.value();
924            if let Some(field) = fields
925                .iter()
926                .find(|field| !field.attrs.skip && field.endpoint == name)
927            {
928                ListingEntry::Field(field)
929            } else if let Some(method) = methods.iter().find(|method| method.endpoint == name) {
930                ListingEntry::Signature(method)
931            } else {
932                ListingEntry::ImplNamed(key.clone())
933            }
934        })
935        .collect()
936}
937
938/// Check a `#[repe(listing_order(..))]` list against everything this macro can
939/// see: the fields, and the struct-level `#[repe(methods(..))]` entries.
940///
941/// A name the macro does not recognize is only rejected when there is no
942/// `#[repe::methods]` block to have declared it — with one, the endpoints of
943/// that block are the third source, and they are checked by the `const`
944/// assertion the handshake emits. Everything reachable here is rejected here,
945/// because only this side can name the offending key in the message.
946fn validate_listing_order(
947    order: &ListingOrder,
948    declared: &[(&str, Span)],
949    from_impl_block: bool,
950) -> syn::Result<()> {
951    let mut seen: Vec<String> = Vec::new();
952    for key in &order.keys {
953        let name = key.value();
954        if seen.contains(&name) {
955            return Err(syn::Error::new_spanned(
956                key,
957                format!(
958                    "`{name}` is named twice in `#[repe(listing_order(..))]`; the listing emits \
959                     each key once, so the second position could never be used"
960                ),
961            ));
962        }
963        if !from_impl_block && !declared.iter().any(|(endpoint, _)| *endpoint == name) {
964            return Err(syn::Error::new_spanned(
965                key,
966                format!(
967                    "`{name}` is not an endpoint on this struct, so the listing has nothing to \
968                     emit for it"
969                ),
970            ));
971        }
972        seen.push(name);
973    }
974
975    for (endpoint, span) in declared {
976        if !seen.iter().any(|name| name == endpoint) {
977            return Err(syn::Error::new(
978                *span,
979                format!(
980                    "`{endpoint}` is missing from `#[repe(listing_order(..))]`, which names the \
981                     whole-object listing's keys in full. An omitted endpoint would disappear \
982                     from every whole-object read while still answering on its own path."
983                ),
984            ));
985        }
986    }
987    Ok(())
988}
989
990/// The `const` block that decides, at compile time, whether an ordered
991/// impl-block key is a published method (listed by its signature) or a
992/// field-shaped accessor (listed by its value).
993fn impl_named_signature(name: &LitStr, repe: &TokenStream2) -> TokenStream2 {
994    quote! {
995        const {
996            #repe::structs::listed_signature(
997                <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES,
998                #name,
999            )
1000        }
1001    }
1002}
1003
1004/// The `"/endpoint"` literal every arm names in its error paths.
1005fn endpoint_path(endpoint: &str) -> LitStr {
1006    LitStr::new(&format!("/{endpoint}"), Span::call_site())
1007}
1008
1009/// Write one `"key": value` entry.
1010///
1011/// One form for both borrows: writing cannot fail, so there is no failure to
1012/// report differently.
1013fn listing_entry(key: TokenStream2, value: TokenStream2) -> TokenStream2 {
1014    quote! { __repe_obj.entry(#key, &#value); }
1015}
1016
1017/// The response to a read of the whole struct: every field, plus every method
1018/// published as its signature string.
1019///
1020/// Both listings — the exclusive one and the shared one — are this one walk of
1021/// one resolved entry list, so they cannot disagree about *what* is emitted or
1022/// in what order.
1023///
1024/// Key order used to be the one thing they could disagree about, because a third
1025/// form assembled a `serde_json::Map` and sorted its keys. That form is gone
1026/// with `serde_json::Value`, so declaration order and
1027/// `#[repe(listing_order(..))]` now reach every frame a client sees.
1028fn build_listing(
1029    entries: &[ListingEntry<'_>],
1030    repe: &TokenStream2,
1031    borrow: Borrow,
1032) -> TokenStream2 {
1033    let mut emitted = Vec::new();
1034    // The object's member count, which BEVE needs in the header before any
1035    // member. Not a literal: the two `Impl*` entries list a `const` slice whose
1036    // length the deriving crate's own impl block settles. It is still a const
1037    // expression, so this folds to a constant at the call site.
1038    let mut fixed = 0usize;
1039    let mut variable: Vec<TokenStream2> = Vec::new();
1040
1041    for entry in entries {
1042        match entry {
1043            ListingEntry::ImplSignatures => variable.push(quote! {
1044                <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES.len()
1045            }),
1046            ListingEntry::ImplAccessors => variable.push(quote! {
1047                <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS.len()
1048            }),
1049            _ => fixed += 1,
1050        }
1051        emitted.push(match entry {
1052            ListingEntry::Field(field) => {
1053                let key = LitStr::new(&field.endpoint, Span::call_site());
1054                let ident = &field.ident;
1055                if field.attrs.nested {
1056                    // The child writes into a *nested* body, so the frame stays
1057                    // JSON no matter what the child would emit on its own.
1058                    let call = borrow.child_call(
1059                        repe,
1060                        &field.ty,
1061                        ident,
1062                        quote! { &[], None },
1063                        quote! { __repe_nested },
1064                    );
1065                    borrow.entry_with(
1066                        quote! { #key },
1067                        borrow.prepend(repe, call, quote! { #key }),
1068                    )
1069                } else {
1070                    // A `#[repe(typed)]` field is a plain JSON array here,
1071                    // because the enclosing object has already committed the
1072                    // frame to JSON.
1073                    listing_entry(quote! { #key }, quote! { self.#ident })
1074                }
1075            }
1076            ListingEntry::Signature(method) => {
1077                let key = LitStr::new(&method.endpoint, Span::call_site());
1078                let signature = LitStr::new(&method.signature_display, Span::call_site());
1079                listing_entry(quote! { #key }, quote! { #signature })
1080            }
1081            ListingEntry::ImplNamed(name) => {
1082                let resolved = impl_named_signature(name, repe);
1083                let accessor =
1084                    borrow.entry_with(quote! { #name }, borrow.accessor_call(repe, quote! { #name }));
1085                let signature = listing_entry(quote! { #name }, quote! { __repe_signature });
1086                quote! {
1087                    match #resolved {
1088                        ::core::option::Option::Some(__repe_signature) => { #signature }
1089                        ::core::option::Option::None => { #accessor }
1090                    }
1091                }
1092            }
1093            ListingEntry::ImplSignatures => {
1094                let entry = listing_entry(quote! { name }, quote! { signature });
1095                quote! {
1096                    for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
1097                        #entry
1098                    }
1099                }
1100            }
1101            // A field-shaped endpoint is listed the way a field is: by its
1102            // value. The value has to come back through the method table rather
1103            // than from a getter call emitted here, because this derive cannot
1104            // see the impl block and so does not know a single getter's name —
1105            // the endpoint list is all it has. That indirection costs a match
1106            // scan per accessor, so a whole-object read of a struct with many
1107            // accessors is quadratic in the endpoint count; the same read of an
1108            // all-field struct is not.
1109            //
1110            // A getter that returns `Err` fails the whole listing. Writing a
1111            // field cannot fail any more, so a getter is the only entry that can
1112            // — which is why one meant to be listed should report a sentinel
1113            // rather than an error.
1114            ListingEntry::ImplAccessors => {
1115                let accessor =
1116                    borrow.entry_with(quote! { name }, borrow.accessor_call(repe, quote! { name }));
1117                quote! {
1118                    for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
1119                        #accessor
1120                    }
1121                }
1122            }
1123        });
1124    }
1125
1126    let count = quote! { #fixed #( + #variable)* };
1127    borrow.wrap(&emitted, count)
1128}
1129
1130// ---------------------------------------------------------------------------
1131// Field arms
1132// ---------------------------------------------------------------------------
1133
1134/// One dispatch arm per field, under either borrow.
1135///
1136/// A leaf serializes itself; a nested field forwards to its child with this
1137/// field's endpoint prefixed onto any error path it produces; a write lands in
1138/// the live field, is refused outright when the field is `#[repe(readonly)]`, or
1139/// declines under a shared borrow because it needs `&mut self`.
1140///
1141/// One builder for both borrows. The three places they differ — how an outcome
1142/// is shaped, which method a child is entered through, and what a write that
1143/// needs exclusive access does — are exactly what [`Borrow`] carries, so there
1144/// is nothing left for a second builder to hold. Field arms and *listing* arms
1145/// are still built separately, because there the shapes genuinely diverge: a
1146/// listing entry cannot decline past the guard at its top, and it rewinds.
1147fn build_field_arms(
1148    fields: &[FieldSpec],
1149    repe: &TokenStream2,
1150    borrow: Borrow,
1151) -> Vec<TokenStream2> {
1152    let refuse = refuse_write(repe, borrow);
1153    let subpath = refuse_subpath(repe, borrow);
1154    let ack = borrow.ok(emit_null());
1155    let mut arms = Vec::new();
1156    for field in fields {
1157        if field.attrs.skip {
1158            continue;
1159        }
1160        let key = LitStr::new(&field.endpoint, Span::call_site());
1161        let ident = &field.ident;
1162        let path = endpoint_path(&field.endpoint);
1163
1164        if field.attrs.nested {
1165            // `readonly` on a nested field refuses every write *through* it,
1166            // subpaths included: the attribute says the field cannot be written,
1167            // and a write below it mutates the field just as surely as a write
1168            // at it. Past this guard `body` is `None`, so the descent below is
1169            // the same code either way.
1170            let guard = field.attrs.readonly.then(|| {
1171                quote! {
1172                    if body.is_some() {
1173                        return #refuse;
1174                    }
1175                }
1176            });
1177
1178            // The whole-child write descends, exactly as the whole-child read
1179            // already did. Before this, a write with an empty tail replaced the
1180            // child, and so was the one path on which a child's own
1181            // `RepeStruct` impl was never consulted. That is precisely the path
1182            // where a child backed by a resource has something to say: applying
1183            // a partial object to live state is not the same operation as
1184            // replacing a struct.
1185            //
1186            // A derived child's empty-segments arm reads the body into `*self`,
1187            // which *merges* — a key the body omits keeps the value it had —
1188            // where the replacement it succeeds blanked them. That difference is
1189            // wire-visible on a whole-child write, and it is the behaviour a
1190            // partial update wants.
1191            //
1192            // `tail` *is* the empty slice when it is empty, so there is one call
1193            // here rather than a whole-child branch beside a descent.
1194            let forward = borrow.prepend(
1195                repe,
1196                borrow.child_call(
1197                    repe,
1198                    &field.ty,
1199                    ident,
1200                    quote! { tail, body },
1201                    quote! { out },
1202                ),
1203                quote! { #key },
1204            );
1205            arms.push(quote! { #key => { #guard #forward } });
1206        } else {
1207            let span = field.ty.span();
1208            let read = borrow.ok(if field.attrs.typed {
1209                emit_typed_slice_spanned(span, quote! { self.#ident })
1210            } else {
1211                emit_value_spanned(span, quote! { self.#ident })
1212            });
1213            let write = match (field.attrs.readonly, borrow) {
1214                (true, _) => quote! { Some(_) => #refuse, },
1215                (false, Borrow::Exclusive) => quote_spanned! {span=>
1216                    Some(__repe_body) => {
1217                        // Glaze's `read_params`: the bytes land in the live
1218                        // field, so a `Vec` or `String` already there keeps its
1219                        // allocation and a key the body omits keeps its value.
1220                        __repe_body.read_into(#path, &mut self.#ident)?;
1221                        #ack
1222                    }
1223                },
1224                // A write needs `&mut self`, so the shared borrow declines and
1225                // the caller retries under the exclusive one.
1226                (false, Borrow::Shared) => quote! { Some(_) => None, },
1227            };
1228            arms.push(quote! {
1229                #key => {
1230                    if !tail.is_empty() {
1231                        return #subpath;
1232                    }
1233                    match body {
1234                        None => #read,
1235                        #write
1236                    }
1237                }
1238            });
1239        }
1240    }
1241    arms
1242}
1243
1244// ---------------------------------------------------------------------------
1245// Method arms
1246// ---------------------------------------------------------------------------
1247
1248/// Which borrow of `self` a generated body has, and so what it returns.
1249///
1250/// One axis, and every generator in this file turns on it. Under `&mut self` a
1251/// body returns `StructResult<..>`: a failure is `Err`, an answer is bare, and
1252/// a `#[repe(nested)]` child is entered through `repe_handle_into`. Under
1253/// `&self` it returns `Option<StructResult<()>>`, because it may decline a path
1254/// that needs exclusive access, so every outcome is wrapped and a child is
1255/// entered through `repe_shared_into`.
1256///
1257/// This used to be two enums — one for the return shape, one for the listing
1258/// form — chosen together at every call site, which is what said they were the
1259/// same distinction. Carrying it as one variant rather than one generator per
1260/// borrow is what makes "the two agree" structural: there is one walk of one
1261/// entry list, so a `#[repe(listing_order(..))]` cannot reach one and not the
1262/// other.
1263#[derive(Clone, Copy)]
1264enum Borrow {
1265    /// `&mut self`, returning `StructResult<..>`.
1266    Exclusive,
1267    /// `&self`, returning `Option<StructResult<()>>`, `None` being a decline.
1268    Shared,
1269}
1270
1271impl Borrow {
1272    /// `err` as an early return.
1273    fn err(self, err: TokenStream2) -> TokenStream2 {
1274        let refusal = self.refuse(err);
1275        quote! { return #refusal; }
1276    }
1277
1278    /// `err` as an expression in this shape — an answer, not a decline.
1279    fn refuse(self, err: TokenStream2) -> TokenStream2 {
1280        match self {
1281            Borrow::Exclusive => quote! { Err(#err) },
1282            Borrow::Shared => quote! { Some(Err(#err)) },
1283        }
1284    }
1285
1286    /// A successful `expr` in this shape.
1287    fn ok(self, expr: TokenStream2) -> TokenStream2 {
1288        match self {
1289            Borrow::Exclusive => expr,
1290            Borrow::Shared => quote! { Some(#expr) },
1291        }
1292    }
1293
1294    /// The `RepeStruct` method a `#[repe(nested)]` child is entered through,
1295    /// under this borrow.
1296    ///
1297    /// `args` is the request being forwarded and `out` the body it writes into:
1298    /// `&[], None` and the enclosing object's nested body when the child is
1299    /// being *listed*, `tail, body` and `out` when a request is being dispatched
1300    /// *into* it.
1301    fn child_call(
1302        self,
1303        repe: &TokenStream2,
1304        ty: &Type,
1305        ident: &Ident,
1306        args: TokenStream2,
1307        out: TokenStream2,
1308    ) -> TokenStream2 {
1309        match self {
1310            Borrow::Exclusive => quote! {
1311                <#ty as #repe::RepeStruct>::repe_handle_into(
1312                    &mut self.#ident, #args, #out,
1313                )
1314            },
1315            Borrow::Shared => quote! {
1316                <#ty as #repe::RepeStruct>::repe_shared_into(
1317                    &self.#ident, #args, #out,
1318                )
1319            },
1320        }
1321    }
1322
1323    /// Prefix a child's endpoint onto any error path it produced. The shared
1324    /// form has an `Option` in the way, since a child may decline.
1325    fn prepend(self, repe: &TokenStream2, call: TokenStream2, key: TokenStream2) -> TokenStream2 {
1326        match self {
1327            Borrow::Exclusive => quote! {
1328                #call.map_err(|err| #repe::structs::prepend_path(err, #key))
1329            },
1330            Borrow::Shared => quote! {
1331                #call.map(|__repe_result| {
1332                    __repe_result.map_err(|err| #repe::structs::prepend_path(err, #key))
1333                })
1334            },
1335        }
1336    }
1337
1338    /// The `RepeMethods` call that reads a field-shaped endpoint's value back.
1339    fn accessor_call(self, repe: &TokenStream2, name: TokenStream2) -> TokenStream2 {
1340        match self {
1341            Borrow::Exclusive => quote! {
1342                <Self as #repe::structs::RepeMethods>::repe_call_into(
1343                    self, &[#name], None, __repe_nested,
1344                )
1345            },
1346            Borrow::Shared => quote! {
1347                <Self as #repe::structs::RepeMethods>::repe_call_shared_into(
1348                    self, &[#name], None, __repe_nested,
1349                )
1350            },
1351        }
1352    }
1353
1354    /// Write one `"key": <value>` entry whose value the callee produces.
1355    ///
1356    /// The shared form uses `entry_try_with`, which rewinds the whole object on
1357    /// a decline and propagates the `None` out of `repe_shared_into` — the
1358    /// safety net for a hand-written table whose `REPE_LISTING_NEEDS_EXCLUSIVE`
1359    /// disagrees with its `repe_call_shared_into`, not a path a derived listing
1360    /// takes.
1361    fn entry_with(self, key: TokenStream2, produce: TokenStream2) -> TokenStream2 {
1362        match self {
1363            Borrow::Exclusive => quote! {
1364                __repe_obj.entry_with(#key, |__repe_nested| { #produce })?;
1365            },
1366            Borrow::Shared => quote! {
1367                if let Err(__repe_err) = __repe_obj.entry_try_with(#key, |__repe_nested| {
1368                    #produce
1369                })? {
1370                    return Some(Err(__repe_err));
1371                }
1372            },
1373        }
1374    }
1375
1376    /// Open the body, run `entries`, and close it.
1377    fn wrap(self, entries: &[TokenStream2], count: TokenStream2) -> TokenStream2 {
1378        match self {
1379            Borrow::Exclusive => quote! {
1380                {
1381                    let mut __repe_obj = out.object(#count);
1382                    #(#entries)*
1383                    __repe_obj.finish();
1384                    Ok(())
1385                }
1386            },
1387            Borrow::Shared => quote! {
1388                {
1389                    let mut __repe_obj = out.object(#count);
1390                    #(#entries)*
1391                    __repe_obj.finish();
1392                    Some(Ok(()))
1393                }
1394            },
1395        }
1396    }
1397}
1398
1399/// The refusal a `#[repe(readonly)]` endpoint gives a write.
1400///
1401/// Emitted *instead of* the write, never before it, so a crate building under
1402/// `#![deny(warnings)]` is not broken by an `unreachable_code` lint on generated
1403/// code. Servable under a shared borrow as well as an exclusive one: refusing a
1404/// write touches nothing, so there is no reason to take the write guard to say
1405/// so.
1406fn refuse_write(repe: &TokenStream2, borrow: Borrow) -> TokenStream2 {
1407    borrow.refuse(quote! {
1408        #repe::StructError::BodyUnexpected {
1409            path: #repe::structs::path_from_segments(segments),
1410        }
1411    })
1412}
1413
1414/// The refusal for a path segment below a leaf endpoint.
1415fn refuse_subpath(repe: &TokenStream2, borrow: Borrow) -> TokenStream2 {
1416    borrow.refuse(quote! {
1417        #repe::StructError::InvalidSubpath {
1418            path: #repe::structs::path_from_segments(segments),
1419        }
1420    })
1421}
1422
1423/// Bind a published method's arguments out of the request body.
1424///
1425/// One argument *is* the body — the shape the wire has always had. Two or more
1426/// arrive as a positional array or a name-keyed object; see `MethodArgs`. A
1427/// method taking none ignores whatever the body holds, which is what makes it
1428/// callable from a bodiless frame.
1429fn decode_method_args(
1430    method: &MethodSpec,
1431    bindings: &[Ident],
1432    repe: &TokenStream2,
1433    borrow: Borrow,
1434) -> TokenStream2 {
1435    if method.args.is_empty() {
1436        return quote! { let _ = &body; };
1437    }
1438    let path = endpoint_path(&method.endpoint);
1439    let missing = borrow.err(quote! {
1440        #repe::StructError::BodyExpected {
1441            path: #repe::structs::path_from_segments(segments),
1442        }
1443    });
1444    // One shape for both borrows. `RequestBody` is `Copy` and borrows the frame,
1445    // so the shared path no longer has to take the body out of an `&mut Option`
1446    // and owe it back to the exclusive retry when it declines.
1447    let take_body = quote! {
1448        let __repe_body = match body {
1449            Some(__repe_body) => __repe_body,
1450            None => { #missing }
1451        };
1452    };
1453    let bad_args = borrow.err(quote! { __repe_err });
1454
1455    if method.args.len() == 1 {
1456        let binding = &bindings[0];
1457        let ty = &method.args[0].1;
1458        return quote! {
1459            #take_body
1460            let #binding: #ty = match __repe_body.read(#path) {
1461                Ok(__repe_value) => __repe_value,
1462                Err(__repe_err) => { #bad_args }
1463            };
1464        };
1465    }
1466
1467    let names: Vec<LitStr> = method
1468        .args
1469        .iter()
1470        .map(|(ident, _)| LitStr::new(&ident.to_string(), Span::call_site()))
1471        .collect();
1472    let decls = method.args.iter().zip(bindings).map(|((_, ty), binding)| {
1473        let bad_args = &bad_args;
1474        quote! {
1475            let #binding: #ty = match __repe_args.next_arg() {
1476                Ok(__repe_value) => __repe_value,
1477                Err(__repe_err) => { #bad_args }
1478            };
1479        }
1480    });
1481    quote! {
1482        #take_body
1483        let mut __repe_args = match #repe::structs::MethodArgs::new(
1484            #path, &[#(#names),*], __repe_body,
1485        ) {
1486            Ok(__repe_args) => __repe_args,
1487            Err(__repe_err) => { #bad_args }
1488        };
1489        #(#decls)*
1490    }
1491}
1492
1493fn build_method_arms(
1494    methods: &[MethodSpec],
1495    repe: &TokenStream2,
1496    borrow: Borrow,
1497) -> Vec<TokenStream2> {
1498    methods
1499        .iter()
1500        .map(|method| build_method_arm(method, repe, borrow))
1501        .collect()
1502}
1503
1504fn build_method_arm(method: &MethodSpec, repe: &TokenStream2, borrow: Borrow) -> TokenStream2 {
1505    let key = LitStr::new(&method.endpoint, Span::call_site());
1506    // A `&mut self` method cannot run under a shared borrow however the frame is
1507    // shaped. Declining costs nothing: the exclusive path answers it exactly as
1508    // it always has.
1509    if matches!(borrow, Borrow::Shared) && !matches!(method.receiver, ReceiverKind::Ref) {
1510        return quote! { #key => None, };
1511    }
1512    let path = endpoint_path(&method.endpoint);
1513    let subpath = refuse_subpath(repe, borrow);
1514    let method_ident = &method.method_ident;
1515
1516    let bindings: Vec<Ident> = (0..method.args.len())
1517        .map(|i| format_ident!("__repe_arg{}", i))
1518        .collect();
1519
1520    let decode_args = decode_method_args(method, &bindings, repe, borrow);
1521
1522    let emit_ok = if method.ret.ok_is_unit() {
1523        emit_null()
1524    } else {
1525        emit_value(quote! { __repe_ok })
1526    };
1527    // Spanned at the method name, because this is the one call in the generated
1528    // code whose receiver comes from a *declaration* rather than from a
1529    // signature: a `#[repe(methods(..))]` entry that says `&self` for a
1530    // `&mut self` method fails here, and the error has to point at that entry
1531    // rather than at `#[derive(RepeStruct)]`.
1532    let invocation = quote_spanned! { method_ident.span()=>
1533        Self::#method_ident(self #(, #bindings)*)
1534    };
1535    let call = borrow.ok(call_and_emit(invocation, &method.ret, emit_ok, repe, &path));
1536
1537    quote! {
1538        #key => {
1539            if !tail.is_empty() {
1540                return #subpath;
1541            }
1542            #decode_args
1543            #call
1544        }
1545    }
1546}
1547
1548/// Call a published method and turn what it returned into a response.
1549///
1550/// `emit_ok` is the response for a success, written against a binding named
1551/// `__repe_ok` when the `Ok` type is not `()`. A declared `Result` turns `Err`
1552/// into a [`StructError::Execution`] naming `path`, rather than serializing the
1553/// `Result` itself.
1554///
1555/// Shared by the method arms and by both halves of an accessor pair, so a
1556/// getter that fails reports it exactly as a method that fails does.
1557fn call_and_emit(
1558    invocation: TokenStream2,
1559    ret: &ReturnSpec,
1560    emit_ok: TokenStream2,
1561    repe: &TokenStream2,
1562    path: &LitStr,
1563) -> TokenStream2 {
1564    if ret.fallible {
1565        let ok_pattern = if ret.ok_is_unit() {
1566            quote! { Ok(_) }
1567        } else {
1568            quote! { Ok(__repe_ok) }
1569        };
1570        quote! {
1571            match #invocation {
1572                #ok_pattern => #emit_ok,
1573                Err(__repe_err) => Err(#repe::StructError::Execution {
1574                    path: String::from(#path),
1575                    message: ::std::string::ToString::to_string(&__repe_err),
1576                }),
1577            }
1578        }
1579    } else if ret.ok_is_unit() {
1580        // Braced so every branch is an *expression*, usable as a match arm body
1581        // as well as a statement tail.
1582        quote! {
1583            {
1584                #invocation;
1585                #emit_ok
1586            }
1587        }
1588    } else {
1589        quote! {
1590            {
1591                let __repe_ok = #invocation;
1592                #emit_ok
1593            }
1594        }
1595    }
1596}
1597
1598// ---------------------------------------------------------------------------
1599// Accessor arms
1600// ---------------------------------------------------------------------------
1601
1602/// One dispatch arm for a field-shaped endpoint, shaped exactly like the arm
1603/// [`build_field_arms`] emits for a real field: no body reads, a body writes,
1604/// and a trailing path segment is a `InvalidSubpath` either way.
1605///
1606/// The only difference is where the value comes from — a getter call instead of
1607/// a field read, a setter call instead of an assignment — which is the whole
1608/// point of the attribute.
1609fn build_accessor_arm(
1610    accessor: &AccessorSpec,
1611    repe: &TokenStream2,
1612    borrow: Borrow,
1613) -> TokenStream2 {
1614    let key = LitStr::new(&accessor.endpoint, Span::call_site());
1615    let path = endpoint_path(&accessor.endpoint);
1616    let subpath = refuse_subpath(repe, borrow);
1617
1618    // No `ok_is_unit` branch: a getter that returns nothing is rejected at
1619    // `parse_impl_method`, since the listing would have no value to show for the
1620    // endpoint. A `&mut self` getter cannot run under a shared borrow.
1621    let read = if matches!(borrow, Borrow::Shared)
1622        && !matches!(accessor.get.receiver, ReceiverKind::Ref)
1623    {
1624        quote! { None }
1625    } else {
1626        let getter = &accessor.get.method_ident;
1627        let emit = if accessor.typed {
1628            emit_typed_slice(quote! { __repe_ok })
1629        } else {
1630            emit_value(quote! { __repe_ok })
1631        };
1632        borrow.ok(call_and_emit(
1633            quote! { Self::#getter(self) },
1634            &accessor.get.ret,
1635            emit,
1636            repe,
1637            &path,
1638        ))
1639    };
1640
1641    // A getter with no setter *is* a read-only endpoint, so the refusal is the
1642    // same one `#[repe(readonly)]` produces on a field. Emitting only the
1643    // rejection — never a write followed by dead code — keeps generated code
1644    // clean under `#![deny(warnings)]`, as the field arms do. A setter mutates
1645    // by construction, so the shared borrow declines it; the refusal above
1646    // mutates nothing and is served either way.
1647    let refuse = refuse_write(repe, borrow);
1648    let write = match (&accessor.set, borrow) {
1649        (None, _) => quote! { Some(_) => #refuse, },
1650        (Some(_), Borrow::Shared) => quote! { Some(_) => None, },
1651        (Some(set), Borrow::Exclusive) => {
1652            let setter = &set.method_ident;
1653            let ty = &set.args[0].1;
1654            let call = call_and_emit(
1655                quote! { Self::#setter(self, __repe_arg) },
1656                &set.ret,
1657                emit_null(),
1658                repe,
1659                &path,
1660            );
1661            quote! {
1662                Some(__repe_body) => {
1663                    let __repe_arg: #ty = __repe_body.read(#path)?;
1664                    #call
1665                }
1666            }
1667        }
1668    };
1669
1670    quote! {
1671        #key => {
1672            if !tail.is_empty() {
1673                return #subpath;
1674            }
1675            match body {
1676                None => #read,
1677                #write
1678            }
1679        }
1680    }
1681}
1682
1683// ---------------------------------------------------------------------------
1684// Shared-borrow path
1685// ---------------------------------------------------------------------------
1686//
1687// `repe_shared_into` and `repe_call_shared_into` serve a request through
1688// `&self`, so a read does not queue behind a long-running call on the same
1689// object. A decline is `None` where the exclusive path has only `Ok`/`Err`, and
1690// the arms themselves are the same generators the exclusive path uses —
1691// `build_method_arm`, `build_accessor_arm` — called with `Borrow::Shared`.
1692//
1693// That is why the two cannot disagree about how a value is serialized or how a
1694// body is read: it is one generator, not two kept in step. They differ only in
1695// whether this borrow serves a path at all, which is decided from the receiver
1696// at the top of each arm. `tests/shared_reads.rs` pins the rest by driving one
1697// struct through both and comparing frames.
1698//
1699// The field and listing arms are still built separately, because there the
1700// shapes genuinely diverge: a nested child is asked to decline in turn, and a
1701// listing rewinds.
1702//
1703// **What decides.** The receiver, not the frame. REPE separates read from write
1704// at the frame level, and taking that as the borrow rule meant a `&self` method
1705// carrying arguments — a long computation, an HTTP fetch, a system call — ran
1706// under the write guard and stalled every read of the object for its duration. That is
1707// the receiver being known at expansion and thrown away. So: a `&self` method is
1708// served here whether or not it carries a body, a `&mut self` one never is, a
1709// field write never is, and a nested child is asked the same question in turn.
1710//
1711// **The body.** It arrives as `Option<RequestBody<'_>>`, a `Copy` view of the
1712// request bytes, so a decline hands the exclusive retry the very same request
1713// at no cost. What an arm must not do is *read from it* before the last point
1714// it could still decline: a read lands in a live member, so a read followed by
1715// a decline is a write the retry would then repeat. `decode_method_args` places
1716// its reads for that reason; a nested child is passed the view directly and
1717// holds the same obligation.
1718//
1719// **Listings settle first.** A listing is the one read that composes many
1720// others, so a decline discovered partway through would leave the entries before
1721// it already executed, and the exclusive retry executes them again — a `&self`
1722// getter over a read counter would report the second call. Rewinding the
1723// response buffer undoes the bytes; it cannot undo a call. Two things can force
1724// that decline, and the guard asks about both: an accessor on this struct whose
1725// getter takes `&mut self`, and a `#[repe(nested)]` child that declines at any
1726// depth. `listing_decline_terms` builds the question;
1727// `RepeStruct::repe_listing_declines` is how a parent asks it of a child. Once
1728// the guard passes, nothing left in the listing can decline.
1729//
1730// Reading one of those endpoints on its own is unaffected: that arm decides from
1731// the receiver, before it calls anything.
1732
1733/// The terms of "a shared whole-object listing of this struct declines",
1734/// OR'd together by both places that need the answer: the guard at the top of
1735/// the listing, and the `RepeStruct::repe_listing_declines` this struct
1736/// publishes for any parent that nests it.
1737///
1738/// Two things can force a listing exclusive, and they are not the same thing:
1739///
1740/// * an accessor on **this** struct whose getter takes `&mut self`, which
1741///   `#[repe::methods]` reports as `REPE_LISTING_NEEDS_EXCLUSIVE`; and
1742/// * a `#[repe(nested)]` child that declines, at any depth — the parent's
1743///   listing composes the child's, so the child's refusal is the parent's.
1744///
1745/// The second is why this cannot be read off `RepeMethods` alone. A child is
1746/// listed *before* this struct's own accessors are read, so a child discovered
1747/// to decline partway through would leave those already invoked — and the
1748/// exclusive retry invokes them again. Asking every child up front is what makes
1749/// the guard's promise ("nothing after this point can decline") true rather than
1750/// true by accident of declaration order.
1751///
1752/// A leaf field contributes no term: it is written straight into the response
1753/// and has no impl of its own to ask.
1754///
1755/// An empty result means the constant `false`: a struct of plain fields, or one
1756/// whose nesting and accessors all read shared. The caller emits no guard at all
1757/// for that, so the common case costs nothing.
1758/// The terms of "some path on this struct answers a body-carrying frame under a
1759/// shared borrow", OR'd into the `RepeStruct::REPE_SHARED_SERVES_BODIES` this
1760/// struct publishes.
1761///
1762/// The const is a hint the router reads before it takes the read lock, so the
1763/// only cost of a wrong answer is concurrency: everything the shared borrow
1764/// answers with a body, the exclusive path answers identically. That makes `true`
1765/// the safe direction, and this over-approximates deliberately rather than
1766/// tracking every arm shape exactly.
1767///
1768/// Four things put a body-carrying answer on this struct:
1769///
1770/// * `#[repe(readonly)]` on the struct, whose whole-object refusal is servable
1771///   shared — there is no reason to take the write guard to say no;
1772/// * `#[repe(readonly)]` on a field, for the same reason one level down;
1773/// * a struct-listed `&self` method that takes arguments, which is a call
1774///   rather than a mutation and is exactly what the shared path exists for; and
1775/// * a `#[repe(nested)]` child with any of the above, at any depth.
1776///
1777/// The impl block's own methods and accessors are a fifth, but the derive
1778/// cannot see them; `#[repe::methods]` computes
1779/// `RepeMethods::REPE_SHARED_SERVES_BODIES` and this ORs it in.
1780///
1781/// A leaf field contributes no term unless it is read-only: a write to one is a
1782/// write, and needs `&mut self`.
1783///
1784/// An empty result means the constant `false` — a struct of plain fields whose
1785/// every write needs the exclusive borrow, which is the shape the skip is for.
1786fn shared_body_terms(
1787    fields: &[FieldSpec],
1788    struct_attrs: &StructAttrs,
1789    from_impl_block: bool,
1790    repe: &TokenStream2,
1791) -> Vec<TokenStream2> {
1792    // A refusal that needs no state, or a call that needs no mutation: both are
1793    // answers this struct can give without the write guard.
1794    if struct_attrs.no_replace
1795        || struct_attrs
1796            .methods
1797            .iter()
1798            .any(|m| matches!(m.receiver, ReceiverKind::Ref) && !m.args.is_empty())
1799    {
1800        return vec![quote! { true }];
1801    }
1802
1803    let mut terms = Vec::new();
1804    if from_impl_block {
1805        terms.push(quote! {
1806            <Self as #repe::structs::RepeMethods>::REPE_SHARED_SERVES_BODIES
1807        });
1808    }
1809    for field in fields {
1810        if field.attrs.skip {
1811            continue;
1812        }
1813        if field.attrs.readonly {
1814            return vec![quote! { true }];
1815        }
1816        if !field.attrs.nested {
1817            continue;
1818        }
1819        let ty = &field.ty;
1820        terms.push(quote! {
1821            <#ty as #repe::RepeStruct>::REPE_SHARED_SERVES_BODIES
1822        });
1823    }
1824    terms
1825}
1826
1827fn listing_decline_terms(
1828    fields: &[FieldSpec],
1829    from_impl_block: bool,
1830    repe: &TokenStream2,
1831) -> Vec<TokenStream2> {
1832    let mut terms = Vec::new();
1833    if from_impl_block {
1834        terms.push(quote! {
1835            <Self as #repe::structs::RepeMethods>::REPE_LISTING_NEEDS_EXCLUSIVE
1836        });
1837    }
1838    for field in fields {
1839        if field.attrs.skip || !field.attrs.nested {
1840            continue;
1841        }
1842        let ident = &field.ident;
1843        let ty = &field.ty;
1844        terms.push(quote! {
1845            <#ty as #repe::RepeStruct>::repe_listing_declines(&self.#ident)
1846        });
1847    }
1848    terms
1849}
1850
1851// ---------------------------------------------------------------------------
1852// #[repe::methods]
1853// ---------------------------------------------------------------------------
1854
1855fn expand_methods(mut item_impl: ItemImpl) -> TokenStream2 {
1856    let repe = repe_crate_path();
1857    // Strip our attributes before anything can fail, so the impl block is
1858    // re-emittable either way — `repe` is not a registered attribute on a plain
1859    // inherent impl, and leaving one behind would bury the real error.
1860    let mut stripped = Vec::new();
1861    for item in &mut item_impl.items {
1862        if let ImplItem::Fn(func) = item {
1863            stripped.push(take_method_attrs(&mut func.attrs));
1864        }
1865    }
1866
1867    match collect_methods(&item_impl, stripped) {
1868        Ok(published) => methods_impl(&item_impl, &published, &repe, false),
1869        Err(err) => {
1870            // Emit the diagnostic *and* a table with nothing in it, marked as
1871            // the recovery shape. Failing with the error alone would drop the
1872            // `RepeMethods` impl and add a second, misleading "no
1873            // `#[repe::methods]` impl block" error on top of the real one; the
1874            // marker is what lets the compile-time checks against these tables
1875            // stand down without also standing down for a block that compiles
1876            // and happens to publish nothing.
1877            let error = err.to_compile_error();
1878            let empty = methods_impl(&item_impl, &PublishedItems::default(), &repe, true);
1879            quote! {
1880                #error
1881                #empty
1882            }
1883        }
1884    }
1885}
1886
1887/// Which of the three published shapes one signature in a `#[repe::methods]`
1888/// block takes.
1889enum Published {
1890    /// An ordinary endpoint: the request body carries the arguments.
1891    Method,
1892    /// The read half of a field-shaped endpoint, carrying whether the getter
1893    /// asked for the BEVE typed-slice encoding.
1894    Get { typed: bool },
1895    /// The write half of a field-shaped endpoint.
1896    Set,
1897}
1898
1899/// A **field-shaped endpoint** backed by a getter/setter pair.
1900///
1901/// The wire shape is a field's — a bodiless request reads it, a request with a
1902/// body writes it, and the whole-struct listing shows its value — while the
1903/// implementation is two methods. That is the one endpoint shape a struct
1904/// cannot express by naming a field: a value that is derived, unit-converted,
1905/// or backed by a resource rather than by storage.
1906struct AccessorSpec {
1907    endpoint: String,
1908    /// The read half. Every accessor has one: without it the whole-struct
1909    /// listing would have no value to show for the endpoint.
1910    get: MethodSpec,
1911    /// `#[repe(typed)]` on the getter: encode the value as a BEVE typed numeric
1912    /// array, exactly as the field attribute of the same name does.
1913    typed: bool,
1914    /// The write half, absent for a read-only accessor — which is how a
1915    /// read-only field-shaped endpoint is spelled: there is no setter to call,
1916    /// so a write is refused the way `#[repe(readonly)]` refuses one.
1917    set: Option<MethodSpec>,
1918}
1919
1920/// Everything one `#[repe::methods]` block publishes.
1921#[derive(Default)]
1922struct PublishedItems {
1923    methods: Vec<MethodSpec>,
1924    accessors: Vec<AccessorSpec>,
1925}
1926
1927/// Reject two `#[repe(get = "x")]` methods, or two `#[repe(set = "x")]` methods,
1928/// claiming one endpoint.
1929///
1930/// Separate from [`reject_duplicate_endpoints`] only for the remedy: that one
1931/// recommends `#[repe(rename = "...")]`, which is itself a hard error on an
1932/// accessor half.
1933fn reject_duplicate_accessor_half<'a>(
1934    halves: &(impl Iterator<Item = &'a MethodSpec> + Clone),
1935    key: &str,
1936) -> syn::Result<()> {
1937    let mut seen: Vec<&str> = Vec::new();
1938    for spec in halves.clone() {
1939        if seen.contains(&spec.endpoint.as_str()) {
1940            return Err(syn::Error::new(
1941                spec.method_ident.span(),
1942                format!(
1943                    "two methods claim `#[repe({key} = \"{endpoint}\")]`; a field-shaped \
1944                     endpoint has one read half and one write half, so one of these could never \
1945                     be called. Give one of them a different endpoint.",
1946                    endpoint = spec.endpoint
1947                ),
1948            ));
1949        }
1950        seen.push(&spec.endpoint);
1951    }
1952    Ok(())
1953}
1954
1955/// Validate every method in the block and collect what will be published.
1956fn collect_methods(
1957    item_impl: &ItemImpl,
1958    stripped: Vec<syn::Result<MethodAttrs>>,
1959) -> syn::Result<PublishedItems> {
1960    if let Some((_, path, _)) = &item_impl.trait_ {
1961        return Err(syn::Error::new_spanned(
1962            path,
1963            "`#[repe::methods]` applies to an inherent impl block, not a trait impl",
1964        ));
1965    }
1966
1967    let mut methods: Vec<MethodSpec> = Vec::new();
1968    // Halves arrive in source order and are paired afterwards, so the two halves
1969    // of one endpoint need not sit next to each other.
1970    let mut getters: Vec<(MethodSpec, bool)> = Vec::new();
1971    let mut setters: Vec<MethodSpec> = Vec::new();
1972    let mut stripped = stripped.into_iter();
1973    for item in &item_impl.items {
1974        let ImplItem::Fn(func) = item else {
1975            continue;
1976        };
1977        let attrs = stripped
1978            .next()
1979            .expect("one parsed attribute set per impl fn")?;
1980        if attrs.skip {
1981            continue;
1982        }
1983        let Some((published, spec)) = parse_impl_method(&func.sig, &func.attrs, attrs)? else {
1984            continue;
1985        };
1986        match published {
1987            Published::Method => methods.push(spec),
1988            Published::Get { typed } => getters.push((spec, typed)),
1989            Published::Set => setters.push(spec),
1990        }
1991    }
1992
1993    // Each half is checked on its own, with its own message: the generic
1994    // duplicate-endpoint error recommends `#[repe(rename = "...")]`, which is a
1995    // hard error on an accessor half, so it would send the reader somewhere the
1996    // macro refuses to follow.
1997    reject_duplicate_accessor_half(&getters.iter().map(|(spec, _)| spec), "get")?;
1998    reject_duplicate_accessor_half(&setters.iter(), "set")?;
1999
2000    let mut accessors: Vec<AccessorSpec> = Vec::new();
2001    for (get, typed) in getters {
2002        let set = setters
2003            .iter()
2004            .position(|spec| spec.endpoint == get.endpoint)
2005            .map(|index| setters.remove(index));
2006        accessors.push(AccessorSpec {
2007            endpoint: get.endpoint.clone(),
2008            get,
2009            typed,
2010            set,
2011        });
2012    }
2013    // A setter with no getter left over. Publishing it would give the endpoint a
2014    // value the listing cannot show and a client cannot read back, so the shape
2015    // is refused rather than half-served.
2016    if let Some(orphan) = setters.first() {
2017        return Err(syn::Error::new(
2018            orphan.method_ident.span(),
2019            format!(
2020                "`#[repe(set = \"{endpoint}\")]` has no matching \
2021                 `#[repe(get = \"{endpoint}\")]` in this block: a field-shaped endpoint that \
2022                 cannot be read has no value for the whole-struct listing to show. Add the read \
2023                 half, or publish this as an ordinary method.",
2024                endpoint = orphan.endpoint
2025            ),
2026        ));
2027    }
2028
2029    let endpoints: Vec<(&str, Span)> = methods
2030        .iter()
2031        .map(|spec| (spec.endpoint.as_str(), spec.method_ident.span()))
2032        .chain(
2033            accessors
2034                .iter()
2035                .map(|spec| (spec.endpoint.as_str(), spec.get.method_ident.span())),
2036        )
2037        .collect();
2038    reject_duplicate_endpoints(&endpoints)?;
2039    Ok(PublishedItems { methods, accessors })
2040}
2041
2042/// The impl block itself plus the `RepeMethods` table for `published`.
2043fn methods_impl(
2044    item_impl: &ItemImpl,
2045    published: &PublishedItems,
2046    repe: &TokenStream2,
2047    recovered: bool,
2048) -> TokenStream2 {
2049    let self_ty = &item_impl.self_ty;
2050    let (impl_generics, _ty_generics, where_clause) = item_impl.generics.split_for_impl();
2051
2052    let signatures = published.methods.iter().map(|spec| {
2053        let endpoint = LitStr::new(&spec.endpoint, Span::call_site());
2054        let signature = LitStr::new(&spec.signature_display, Span::call_site());
2055        quote! { (#endpoint, #signature) }
2056    });
2057    let accessor_endpoints = published
2058        .accessors
2059        .iter()
2060        .map(|spec| LitStr::new(&spec.endpoint, Span::call_site()));
2061    // The shared whole-struct listing reads every accessor back through
2062    // `repe_call_shared_into`, which serves a getter only when it takes `&self`.
2063    // One `&mut self` getter is enough to make a decline possible partway
2064    // through the listing, and a decline discovered there would leave the
2065    // getters before it invoked twice — so the listing declines at the top
2066    // instead. Every getter being `&self` means no entry can decline, which is
2067    // what lets the listing be served shared.
2068    let listing_needs_exclusive = published
2069        .accessors
2070        .iter()
2071        .any(|spec| !matches!(spec.get.receiver, ReceiverKind::Ref));
2072
2073    // Which endpoints in this table answer a frame that carries a body without
2074    // the exclusive borrow: a `&self` method taking arguments (a call, not a
2075    // mutation), a `&self` setter, and a read-only accessor, whose refusal
2076    // needs no state to give. Everything else declines, and the router can skip
2077    // the attempt when nothing here is any of the three.
2078    let shared_serves_bodies = published
2079        .methods
2080        .iter()
2081        .any(|spec| matches!(spec.receiver, ReceiverKind::Ref) && !spec.args.is_empty())
2082        || published.accessors.iter().any(|spec| match &spec.set {
2083            Some(set) => matches!(set.receiver, ReceiverKind::Ref),
2084            None => true,
2085        });
2086
2087    let mut bodies = Vec::new();
2088    {
2089        let arms = build_method_arms(&published.methods, repe, Borrow::Exclusive)
2090            .into_iter()
2091            .chain(
2092                published
2093                    .accessors
2094                    .iter()
2095                    .map(|accessor| build_accessor_arm(accessor, repe, Borrow::Exclusive)),
2096            )
2097            .collect::<Vec<_>>();
2098        bodies.push(quote! {
2099            fn repe_call_into(
2100                &mut self,
2101                segments: &[&str],
2102                body: Option<#repe::structs::RequestBody<'_>>,
2103                out: &mut #repe::structs::ResponseBody<'_>,
2104            ) -> #repe::structs::StructResult<()> {
2105                let Some((head, tail)) = segments.split_first() else {
2106                    return Err(#repe::StructError::InvalidPath { path: String::from("") });
2107                };
2108                let _ = (&out, tail, &body);
2109                match *head {
2110                    #(#arms)*
2111                    _ => Err(#repe::StructError::InvalidPath {
2112                        path: #repe::structs::path_from_segments(segments),
2113                    }),
2114                }
2115            }
2116        });
2117    }
2118
2119    let shared_arms = build_method_arms(&published.methods, repe, Borrow::Shared)
2120        .into_iter()
2121        .chain(
2122            published
2123                .accessors
2124                .iter()
2125                .map(|accessor| build_accessor_arm(accessor, repe, Borrow::Shared)),
2126        )
2127        .collect::<Vec<_>>();
2128    let shared_invalid_root = quote! {
2129        Some(Err(#repe::StructError::InvalidPath { path: String::from("") }))
2130    };
2131    let shared_invalid_path = quote! {
2132        Some(Err(#repe::StructError::InvalidPath {
2133            path: #repe::structs::path_from_segments(segments),
2134        }))
2135    };
2136    bodies.push(quote! {
2137        fn repe_call_shared_into(
2138            &self,
2139            segments: &[&str],
2140            body: Option<#repe::structs::RequestBody<'_>>,
2141            out: &mut #repe::structs::ResponseBody<'_>,
2142        ) -> Option<#repe::structs::StructResult<()>> {
2143            let Some((head, tail)) = segments.split_first() else {
2144                return #shared_invalid_root;
2145            };
2146            // Every arm may be a decline, in which case none of these is read.
2147            let _ = (&out, tail, &body);
2148            match *head {
2149                #(#shared_arms)*
2150                _ => #shared_invalid_path,
2151            }
2152        }
2153    });
2154
2155    // No handshake assertion to emit: `MethodsDeclared` is a supertrait of
2156    // `RepeMethods`, so this impl cannot compile unless the struct declared
2157    // `#[repe(methods)]`.
2158    quote! {
2159        #item_impl
2160
2161        impl #impl_generics #repe::structs::RepeMethods for #self_ty #where_clause {
2162            const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)] =
2163                &[#(#signatures),*];
2164
2165            const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] =
2166                &[#(#accessor_endpoints),*];
2167
2168            const REPE_LISTING_NEEDS_EXCLUSIVE: bool = #listing_needs_exclusive;
2169
2170            const REPE_SHARED_SERVES_BODIES: bool = #shared_serves_bodies;
2171
2172            const REPE_TABLE_RECOVERED: bool = #recovered;
2173
2174            #(#bodies)*
2175        }
2176    }
2177}
2178
2179#[derive(Default)]
2180struct MethodAttrs {
2181    rename: Option<String>,
2182    skip: bool,
2183    /// `#[repe(get = "endpoint")]`: this method is the read half of the
2184    /// field-shaped endpoint it names.
2185    get: Option<LitStr>,
2186    /// `#[repe(set = "endpoint")]`: this method is the write half.
2187    set: Option<LitStr>,
2188    /// `#[repe(typed)]` on a getter, the accessor twin of the field attribute.
2189    /// Carries its own span, which is the only one an error about it can point
2190    /// at when there is no `get`/`set` literal to blame.
2191    typed: Option<Span>,
2192}
2193
2194impl MethodAttrs {
2195    /// The endpoint this method serves as an accessor half, if it is one.
2196    fn accessor_endpoint(&self) -> Option<&LitStr> {
2197        self.get.as_ref().or(self.set.as_ref())
2198    }
2199}
2200
2201/// Read the `#[repe(..)]` attributes off a method in a `#[repe::methods]` block
2202/// and strip them, since the inherent impl is re-emitted verbatim and `repe` is
2203/// not a registered attribute there.
2204fn take_method_attrs(attrs: &mut Vec<Attribute>) -> syn::Result<MethodAttrs> {
2205    let mut parsed = MethodAttrs::default();
2206    for attr in attrs.iter() {
2207        if !attr.path().is_ident("repe") {
2208            continue;
2209        }
2210        attr.parse_nested_meta(|meta| {
2211            if parse_shared_meta(&meta, &mut parsed.rename, &mut parsed.skip)? {
2212                return Ok(());
2213            }
2214            if meta.path.is_ident("get") {
2215                parsed.get = Some(meta.value()?.parse()?);
2216                return Ok(());
2217            }
2218            if meta.path.is_ident("set") {
2219                parsed.set = Some(meta.value()?.parse()?);
2220                return Ok(());
2221            }
2222            if meta.path.is_ident("typed") {
2223                parsed.typed = Some(meta.path.span());
2224                return Ok(());
2225            }
2226            Err(meta.error("unsupported `repe` method attribute"))
2227        })?;
2228    }
2229    attrs.retain(|attr| !attr.path().is_ident("repe"));
2230    validate_method_attrs(&parsed)?;
2231    Ok(parsed)
2232}
2233
2234/// Reject combinations of method attributes that contradict each other, before
2235/// any of them reaches code generation.
2236fn validate_method_attrs(attrs: &MethodAttrs) -> syn::Result<()> {
2237    if let (Some(get), Some(_)) = (&attrs.get, &attrs.set) {
2238        return Err(syn::Error::new_spanned(
2239            get,
2240            "a method is either the `get` half of a field-shaped endpoint or the `set` half, not \
2241             both: one takes no arguments and returns the value, the other takes the value and \
2242             returns nothing",
2243        ));
2244    }
2245    let Some(endpoint) = attrs.accessor_endpoint() else {
2246        if let Some(typed) = attrs.typed {
2247            return Err(syn::Error::new(
2248                typed,
2249                "`#[repe(typed)]` applies to the `get` half of a field-shaped endpoint; an \
2250                 ordinary method's return value is always encoded as JSON",
2251            ));
2252        }
2253        return Ok(());
2254    };
2255    if attrs.skip {
2256        return Err(syn::Error::new_spanned(
2257            endpoint,
2258            "`#[repe(skip)]` and `#[repe(get/set)]` contradict each other: one withholds the \
2259             method from the served surface, the other publishes it",
2260        ));
2261    }
2262    if attrs.rename.is_some() {
2263        return Err(syn::Error::new_spanned(
2264            endpoint,
2265            "`#[repe(rename = \"...\")]` has nothing to rename here: the endpoint of a \
2266             field-shaped accessor is the name given to `get`/`set`",
2267        ));
2268    }
2269    if attrs.typed.is_some() && attrs.set.is_some() {
2270        return Err(syn::Error::new_spanned(
2271            endpoint,
2272            "`#[repe(typed)]` describes how a value is *encoded* into a response, so it belongs \
2273             on the `get` half; a `set` decodes whatever the client sent",
2274        ));
2275    }
2276    let value = endpoint.value();
2277    if value.is_empty() {
2278        return Err(syn::Error::new_spanned(
2279            endpoint,
2280            "a field-shaped endpoint needs a name",
2281        ));
2282    }
2283    if value.contains('/') {
2284        return Err(syn::Error::new_spanned(
2285            endpoint,
2286            "a field-shaped endpoint is one path segment below the struct root, so it cannot \
2287             contain `/`",
2288        ));
2289    }
2290    Ok(())
2291}
2292
2293/// Turn one signature from a `#[repe::methods]` block into a published method,
2294/// or `Ok(None)` for an associated function that is not one.
2295fn parse_impl_method(
2296    sig: &Signature,
2297    remaining_attrs: &[Attribute],
2298    attrs: MethodAttrs,
2299) -> syn::Result<Option<(Published, MethodSpec)>> {
2300    let Some(FnArg::Receiver(receiver)) = sig.inputs.first() else {
2301        // An associated function has no instance to dispatch on. `Self::new()`
2302        // and friends belong in the block; they are simply not endpoints.
2303        if let Some(endpoint) = attrs.accessor_endpoint() {
2304            return Err(syn::Error::new_spanned(
2305                endpoint,
2306                "a field-shaped endpoint is served by a method on the instance, so its halves \
2307                 need a `&self` or `&mut self` receiver",
2308            ));
2309        }
2310        return Ok(None);
2311    };
2312
2313    // Conditional compilation is applied *after* attribute macros run, so a
2314    // published `#[cfg]` method would be dispatched to whether or not it exists
2315    // — and the resulting error points at the user's own definition saying it
2316    // is missing. Refuse instead of generating that.
2317    if let Some(cfg) = remaining_attrs
2318        .iter()
2319        .find(|attr| attr.path().is_ident("cfg") || attr.path().is_ident("cfg_attr"))
2320    {
2321        return Err(syn::Error::new_spanned(
2322            cfg,
2323            "`#[repe::methods]` cannot publish a conditionally-compiled method: `#[cfg]` is \
2324             applied after this macro runs, so the endpoint would be generated even when the \
2325             method is not. Move it to a plain `impl` block, or add `#[repe(skip)]` and expose \
2326             an unconditional wrapper.",
2327        ));
2328    }
2329
2330    if receiver.reference.is_none() {
2331        return Err(syn::Error::new_spanned(
2332            receiver,
2333            "`#[repe::methods]` needs a `&self` or `&mut self` receiver; a method that consumes `self` cannot be called on a served object (add `#[repe(skip)]` to exclude it)",
2334        ));
2335    }
2336    let kind = if receiver.mutability.is_some() {
2337        ReceiverKind::Mut
2338    } else {
2339        ReceiverKind::Ref
2340    };
2341
2342    if sig.asyncness.is_some() {
2343        return Err(syn::Error::new_spanned(
2344            sig.asyncness,
2345            "`#[repe::methods]` cannot publish an async method; the struct router dispatches synchronously (add `#[repe(skip)]` to exclude it)",
2346        ));
2347    }
2348    if sig.unsafety.is_some() {
2349        return Err(syn::Error::new_spanned(
2350            sig.unsafety,
2351            "`#[repe::methods]` cannot publish an unsafe method (add `#[repe(skip)]` to exclude it)",
2352        ));
2353    }
2354    if let Some(variadic) = &sig.variadic {
2355        return Err(syn::Error::new_spanned(
2356            variadic,
2357            "`#[repe::methods]` cannot publish a variadic method (add `#[repe(skip)]` to exclude it)",
2358        ));
2359    }
2360    if sig
2361        .generics
2362        .params
2363        .iter()
2364        .any(|param| !matches!(param, syn::GenericParam::Lifetime(_)))
2365    {
2366        return Err(syn::Error::new_spanned(
2367            &sig.generics,
2368            "`#[repe::methods]` cannot publish a generic method; the dispatch table needs one concrete signature (add `#[repe(skip)]` to exclude it)",
2369        ));
2370    }
2371
2372    // Names come from the signature where there is one to take. A pattern that
2373    // is not an identifier (`_`, a destructuring pattern) gets a positional
2374    // stand-in that cannot collide with a real parameter name, since the two
2375    // share one namespace in an object-form body.
2376    let mut args: Vec<(Ident, Type)> = Vec::new();
2377    for (index, input) in sig.inputs.iter().skip(1).enumerate() {
2378        let FnArg::Typed(pat_type) = input else {
2379            continue;
2380        };
2381        if matches!(&*pat_type.ty, Type::Reference(_)) {
2382            return Err(syn::Error::new_spanned(
2383                &pat_type.ty,
2384                "`#[repe::methods]` needs owned arguments, since each one is deserialized from the request body (use `String` rather than `&str`, or add `#[repe(skip)]` to exclude the method)",
2385            ));
2386        }
2387        if matches!(&*pat_type.ty, Type::ImplTrait(_)) {
2388            return Err(syn::Error::new_spanned(
2389                &pat_type.ty,
2390                "`#[repe::methods]` needs a nameable argument type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
2391            ));
2392        }
2393        let name = match &*pat_type.pat {
2394            syn::Pat::Ident(pat_ident) => pat_ident.ident.clone(),
2395            _ => format_ident!("_{}", index),
2396        };
2397        args.push((name, (*pat_type.ty).clone()));
2398    }
2399
2400    let ret_ty: Type = match &sig.output {
2401        ReturnType::Default => syn::parse_quote! { () },
2402        ReturnType::Type(_, ty) => (**ty).clone(),
2403    };
2404    if matches!(ret_ty, Type::ImplTrait(_)) {
2405        return Err(syn::Error::new_spanned(
2406            &sig.output,
2407            "`#[repe::methods]` needs a nameable return type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
2408        ));
2409    }
2410    let ret = classify_return(&ret_ty);
2411    let signature_display = build_signature_string(kind, &args, &ret);
2412
2413    let (published, endpoint) = match (&attrs.get, &attrs.set) {
2414        (Some(name), _) => {
2415            if !args.is_empty() {
2416                return Err(syn::Error::new_spanned(
2417                    &sig.inputs,
2418                    "the `get` half of a field-shaped endpoint takes no arguments: a client reads \
2419                     it the way it reads a field, with no request body to decode them from",
2420                ));
2421            }
2422            if ret.ok_is_unit() {
2423                return Err(syn::Error::new_spanned(
2424                    &sig.output,
2425                    "the `get` half of a field-shaped endpoint has to return the value; a read \
2426                     that yields nothing has nothing to publish",
2427                ));
2428            }
2429            (
2430                Published::Get {
2431                    typed: attrs.typed.is_some(),
2432                },
2433                name.value(),
2434            )
2435        }
2436        (None, Some(name)) => {
2437            if args.len() != 1 {
2438                return Err(syn::Error::new_spanned(
2439                    &sig.inputs,
2440                    "the `set` half of a field-shaped endpoint takes exactly one argument: the \
2441                     request body *is* the new value, as it is for a field write",
2442                ));
2443            }
2444            if !ret.ok_is_unit() {
2445                return Err(syn::Error::new_spanned(
2446                    &sig.output,
2447                    "the `set` half of a field-shaped endpoint returns nothing (or \
2448                     `Result<(), E>`): a field write is acknowledged with `null`, so a returned \
2449                     value would be silently dropped",
2450                ));
2451            }
2452            (Published::Set, name.value())
2453        }
2454        (None, None) => (
2455            Published::Method,
2456            attrs.rename.unwrap_or_else(|| sig.ident.to_string()),
2457        ),
2458    };
2459
2460    Ok(Some((
2461        published,
2462        MethodSpec {
2463            endpoint,
2464            method_ident: sig.ident.clone(),
2465            receiver: kind,
2466            args,
2467            ret,
2468            signature_display,
2469        },
2470    )))
2471}
2472
2473// ---------------------------------------------------------------------------
2474// `#[repe::plugin]` — the C-ABI plugin exports
2475// ---------------------------------------------------------------------------
2476
2477/// Export a [`Router`] constructor as a REPE C-ABI plugin.
2478///
2479/// (Every `repe` type below is linked by URL rather than by path: this is a
2480/// proc-macro crate, and it does not — cannot — depend on `repe`.)
2481///
2482/// Applied to a zero-argument function returning a `Router`, this emits the five
2483/// symbols a REPE host resolves after `dlopen` — `repe_plugin_interface_version`,
2484/// `repe_plugin_info`, `repe_plugin_init`, `repe_plugin_shutdown`, and
2485/// `repe_plugin_call` — each delegating to a `repe::plugin::PluginRuntime` built
2486/// from your function. See `repe::plugin` for the ABI contract and the
2487/// deployment requirements that come with it.
2488///
2489/// ```ignore
2490/// // Cargo.toml: [lib] crate-type = ["cdylib"]
2491/// use repe::server::Router;
2492///
2493/// #[repe::plugin(root = "/calculator")]
2494/// fn build() -> Router {
2495///     Router::new().with_typed("/calculator/add", |(a, b): (i64, i64)| Ok(a + b))
2496/// }
2497/// ```
2498///
2499/// # Arguments
2500///
2501/// * `root` (required) — the RPC path prefix this plugin claims, reported to the
2502///   host as `repe_plugin_data::root_path`. Must be an absolute JSON Pointer
2503///   prefix: leading `/`, no trailing `/`.
2504/// * `name` — defaults to the crate's `CARGO_PKG_NAME`.
2505/// * `version` — defaults to the crate's `CARGO_PKG_VERSION`.
2506///
2507/// Both defaults exist so the plugin's identity is not restated beside the
2508/// manifest that already carries it, and so it cannot drift from it.
2509///
2510/// The annotated function is left in place and stays callable, which is what
2511/// lets the same router be exercised by ordinary in-process tests.
2512///
2513/// [`Router`]: https://docs.rs/repe/latest/repe/server/struct.Router.html
2514#[proc_macro_attribute]
2515pub fn plugin(attr: TokenStream, item: TokenStream) -> TokenStream {
2516    let mut args = PluginArgs::default();
2517    let parser = syn::meta::parser(|meta| args.parse(meta));
2518    parse_macro_input!(attr with parser);
2519
2520    let item_fn = parse_macro_input!(item as syn::ItemFn);
2521    match expand_plugin(args, item_fn) {
2522        Ok(tokens) => tokens.into(),
2523        Err(err) => err.to_compile_error().into(),
2524    }
2525}
2526
2527#[derive(Default)]
2528struct PluginArgs {
2529    name: Option<LitStr>,
2530    version: Option<LitStr>,
2531    root: Option<LitStr>,
2532}
2533
2534impl PluginArgs {
2535    fn parse(&mut self, meta: ParseNestedMeta) -> syn::Result<()> {
2536        if meta.path.is_ident("name") {
2537            self.name = Some(meta.value()?.parse()?);
2538        } else if meta.path.is_ident("version") {
2539            self.version = Some(meta.value()?.parse()?);
2540        } else if meta.path.is_ident("root") {
2541            self.root = Some(meta.value()?.parse()?);
2542        } else {
2543            return Err(meta.error(
2544                "unknown `#[repe::plugin]` argument; expected `root`, `name`, or `version`",
2545            ));
2546        }
2547        Ok(())
2548    }
2549}
2550
2551/// Reject a string that cannot survive the trip through a C `const char*`.
2552///
2553/// An interior nul truncates the string silently at the host, which surfaces as
2554/// a plugin that loads under a name nobody typed — worth catching here, where
2555/// the literal is in view.
2556fn reject_interior_nul(field: &str, literal: &LitStr) -> syn::Result<()> {
2557    if literal.value().contains('\0') {
2558        return Err(syn::Error::new_spanned(
2559            literal,
2560            format!(
2561                "`{field}` cannot contain a nul byte: it is handed to the host as a C string and \
2562                 would be truncated there"
2563            ),
2564        ));
2565    }
2566    Ok(())
2567}
2568
2569fn expand_plugin(args: PluginArgs, item_fn: syn::ItemFn) -> syn::Result<TokenStream2> {
2570    let repe = repe_crate_path();
2571
2572    let Some(root) = args.root else {
2573        return Err(syn::Error::new(
2574            Span::call_site(),
2575            "`#[repe::plugin]` needs a `root` path prefix, e.g. \
2576             `#[repe::plugin(root = \"/calculator\")]`",
2577        ));
2578    };
2579    reject_interior_nul("root", &root)?;
2580    let root_value = root.value();
2581    if !root_value.starts_with('/') {
2582        return Err(syn::Error::new_spanned(
2583            &root,
2584            "`root` must be an absolute JSON Pointer prefix, so it has to start with `/`",
2585        ));
2586    }
2587    if root_value.len() > 1 && root_value.ends_with('/') {
2588        return Err(syn::Error::new_spanned(
2589            &root,
2590            "`root` must not end with `/`: hosts prefix-match this against request paths, and the \
2591             trailing separator is not part of the prefix",
2592        ));
2593    }
2594
2595    // Default identity to the manifest rather than restating it. `concat!`
2596    // expands `env!` eagerly, so both branches produce one `&'static str`
2597    // literal usable in a `static` initializer.
2598    let name = match &args.name {
2599        Some(name) => {
2600            reject_interior_nul("name", name)?;
2601            quote! { #name }
2602        }
2603        None => quote! { env!("CARGO_PKG_NAME") },
2604    };
2605    let version = match &args.version {
2606        Some(version) => {
2607            reject_interior_nul("version", version)?;
2608            quote! { #version }
2609        }
2610        None => quote! { env!("CARGO_PKG_VERSION") },
2611    };
2612
2613    if !item_fn.sig.inputs.is_empty() {
2614        return Err(syn::Error::new_spanned(
2615            &item_fn.sig.inputs,
2616            "`#[repe::plugin]` applies to a function taking no arguments: the host calls it \
2617             through a C ABI that has nothing to pass",
2618        ));
2619    }
2620    if !item_fn.sig.generics.params.is_empty() {
2621        return Err(syn::Error::new_spanned(
2622            &item_fn.sig.generics,
2623            "`#[repe::plugin]` applies to a non-generic function: the exports are one fixed              set of symbols, so there is no parameter for the host to choose",
2624        ));
2625    }
2626    if item_fn.sig.asyncness.is_some() {
2627        return Err(syn::Error::new_spanned(
2628            &item_fn.sig,
2629            "`#[repe::plugin]` cannot be applied to an `async fn`: `repe_plugin_call` is \
2630             synchronous, with no runtime on the host side of the ABI to drive a future",
2631        ));
2632    }
2633
2634    let build = &item_fn.sig.ident;
2635
2636    Ok(quote! {
2637        #item_fn
2638
2639        #[doc(hidden)]
2640        static __REPE_PLUGIN_INFO: #repe::plugin::RepePluginData = #repe::plugin::RepePluginData {
2641            name: concat!(#name, "\0").as_ptr() as *const ::core::ffi::c_char,
2642            version: concat!(#version, "\0").as_ptr() as *const ::core::ffi::c_char,
2643            root_path: concat!(#root, "\0").as_ptr() as *const ::core::ffi::c_char,
2644        };
2645
2646        #[doc(hidden)]
2647        static __REPE_PLUGIN_RUNTIME: #repe::plugin::PluginRuntime =
2648            #repe::plugin::PluginRuntime::new(#build);
2649
2650        /// `repe_plugin_interface_version`: the ABI version this plugin was
2651        /// built against, which the host checks before reading anything else.
2652        #[unsafe(no_mangle)]
2653        pub extern "C" fn repe_plugin_interface_version() -> ::core::primitive::u32 {
2654            #repe::plugin::REPE_PLUGIN_INTERFACE_VERSION
2655        }
2656
2657        /// `repe_plugin_info`: this plugin's name, version, and claimed RPC path
2658        /// prefix. The pointee is a `static`, so it outlives every call.
2659        #[unsafe(no_mangle)]
2660        pub extern "C" fn repe_plugin_info() -> *const #repe::plugin::RepePluginData {
2661            &__REPE_PLUGIN_INFO
2662        }
2663
2664        /// `repe_plugin_init`: build the router. Optional for the host to call —
2665        /// the first request builds it lazily if this never runs.
2666        #[unsafe(no_mangle)]
2667        pub extern "C" fn repe_plugin_init() -> #repe::plugin::RepeResult {
2668            __REPE_PLUGIN_RUNTIME.init()
2669        }
2670
2671        /// `repe_plugin_shutdown`: refuse further requests.
2672        #[unsafe(no_mangle)]
2673        pub extern "C" fn repe_plugin_shutdown() {
2674            __REPE_PLUGIN_RUNTIME.shutdown()
2675        }
2676
2677        /// `repe_plugin_call`: dispatch one REPE request frame.
2678        ///
2679        /// # Safety
2680        ///
2681        /// `request` must point to `request_size` readable bytes, or be null
2682        /// with a `request_size` of 0. The returned buffer borrows from this
2683        /// thread's response buffer and is invalidated by this thread's next
2684        /// call, so the host must copy before calling again.
2685        #[unsafe(no_mangle)]
2686        pub unsafe extern "C" fn repe_plugin_call(
2687            request: *const ::core::ffi::c_char,
2688            request_size: ::core::primitive::u64,
2689        ) -> #repe::plugin::RepeBuffer {
2690            unsafe { __REPE_PLUGIN_RUNTIME.call(request, request_size) }
2691        }
2692    })
2693}
2694
2695#[cfg(test)]
2696mod tests {
2697    //! The rejections this macro makes at expansion time.
2698    //!
2699    //! Every one of these is a `syn::Error` the user reads as a compile error,
2700    //! and its text is the whole remedy. Asserting on the message here rather
2701    //! than on a captured rustc rendering keeps the check precise about the
2702    //! sentence we wrote and indifferent to how the compiler frames it, which
2703    //! changes between releases.
2704
2705    use super::*;
2706    use syn::parse_quote;
2707
2708    fn field_error(field: syn::Field) -> String {
2709        match parse_field(&field) {
2710            Err(err) => err.to_string(),
2711            Ok(spec) => panic!("`{}` was supposed to be rejected", spec.endpoint),
2712        }
2713    }
2714
2715    fn order(keys: &[&str]) -> ListingOrder {
2716        ListingOrder {
2717            keys: keys
2718                .iter()
2719                .map(|k| LitStr::new(k, Span::call_site()))
2720                .collect(),
2721            span: Span::call_site(),
2722        }
2723    }
2724
2725    fn declared(names: &[&str]) -> Vec<(&'static str, Span)> {
2726        // Leaked so the borrow outlives the call; a test binary's lifetime.
2727        names
2728            .iter()
2729            .map(|n| {
2730                (
2731                    &*Box::leak(n.to_string().into_boxed_str()),
2732                    Span::call_site(),
2733                )
2734            })
2735            .collect()
2736    }
2737
2738    // -----------------------------------------------------------------------
2739    // Field attribute conflicts
2740    // -----------------------------------------------------------------------
2741
2742    #[test]
2743    fn typed_and_nested_are_rejected_together() {
2744        let msg = field_error(parse_quote! {
2745            #[repe(typed, nested)]
2746            child: Child
2747        });
2748        assert!(
2749            msg.contains("BEVE typed array"),
2750            "the message should say why the two cannot combine, got: {msg}"
2751        );
2752    }
2753
2754    #[test]
2755    fn nested_serde_is_rejected_with_a_migration_note() {
2756        // It is rejected during attribute parsing, so it is rejected in every
2757        // combination and there is nothing left for the `typed`/`nested`
2758        // conflict checks to see.
2759        for field in [
2760            parse_quote! { #[repe(nested_serde)] child: Child },
2761            parse_quote! { #[repe(typed, nested_serde)] child: Child },
2762            parse_quote! { #[repe(nested, nested_serde)] child: Child },
2763        ] {
2764            let msg = field_error(field);
2765            assert!(
2766                msg.contains("nested_serde") && msg.contains("structio"),
2767                "the message should name what replaced it, got: {msg}"
2768            );
2769        }
2770    }
2771
2772    #[test]
2773    fn readonly_on_a_struct_is_rejected_and_points_at_no_replace() {
2774        // The word is deliberately unclaimed at struct level: on a field it is
2775        // recursive, and the recursive meaning is the one a struct should get
2776        // if it ever gets one.
2777        let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(readonly)] }];
2778        let msg = match parse_struct_attrs(&attrs) {
2779            Err(err) => err.to_string(),
2780            Ok(_) => panic!("`readonly` on a struct is supposed to be rejected"),
2781        };
2782        assert!(
2783            msg.contains("no_replace") && msg.contains("recursive"),
2784            "the message should name the replacement and say why the two differ, got: {msg}"
2785        );
2786    }
2787
2788    #[test]
2789    fn no_replace_on_a_struct_is_accepted() {
2790        let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(no_replace)] }];
2791        let Ok(parsed) = parse_struct_attrs(&attrs) else {
2792            panic!("`no_replace` is supposed to be accepted");
2793        };
2794        assert!(parsed.no_replace);
2795    }
2796
2797    #[test]
2798    fn readonly_on_a_field_is_still_accepted() {
2799        // Unchanged, and the reason the struct-level spelling had to move.
2800        let field: syn::Field = parse_quote! { #[repe(readonly)] a: u64 };
2801        let Ok(spec) = parse_field(&field) else {
2802            panic!("`readonly` on a field is supposed to be accepted");
2803        };
2804        assert!(spec.attrs.readonly);
2805    }
2806
2807    #[test]
2808    fn an_unknown_field_attribute_is_rejected() {
2809        let msg = field_error(parse_quote! {
2810            #[repe(nonsense)]
2811            a: u64
2812        });
2813        assert!(
2814            msg.contains("unsupported `repe` field attribute"),
2815            "got: {msg}"
2816        );
2817    }
2818
2819    #[test]
2820    fn the_ordinary_combinations_are_accepted() {
2821        for field in [
2822            parse_quote! { #[repe(typed)] values: Vec<f64> },
2823            parse_quote! { #[repe(nested)] child: Child },
2824            parse_quote! { #[repe(nested, readonly)] child: Child },
2825            parse_quote! { #[repe(rename = "other")] a: u64 },
2826            parse_quote! { #[repe(skip)] a: u64 },
2827        ] {
2828            let field: syn::Field = field;
2829            assert!(parse_field(&field).is_ok());
2830        }
2831    }
2832
2833    // -----------------------------------------------------------------------
2834    // `#[repe(listing_order(..))]`, the half checked at macro time
2835    // -----------------------------------------------------------------------
2836
2837    #[test]
2838    fn an_order_naming_every_endpoint_is_accepted() {
2839        let d = declared(&["a", "b"]);
2840        assert!(validate_listing_order(&order(&["b", "a"]), &d, false).is_ok());
2841    }
2842
2843    #[test]
2844    fn a_key_named_twice_is_rejected() {
2845        let d = declared(&["a"]);
2846        let msg = validate_listing_order(&order(&["a", "a"]), &d, false)
2847            .expect_err("a repeated key is rejected")
2848            .to_string();
2849        assert!(msg.contains("named twice"), "got: {msg}");
2850    }
2851
2852    #[test]
2853    fn a_key_that_is_not_an_endpoint_is_rejected() {
2854        let d = declared(&["a"]);
2855        let msg = validate_listing_order(&order(&["a", "typo"]), &d, false)
2856            .expect_err("an unknown key is rejected")
2857            .to_string();
2858        assert!(
2859            msg.contains("`typo` is not an endpoint on this struct"),
2860            "the message should name the offending key, got: {msg}"
2861        );
2862    }
2863
2864    #[test]
2865    fn an_endpoint_missing_from_the_order_is_rejected() {
2866        let d = declared(&["a", "b"]);
2867        let msg = validate_listing_order(&order(&["a"]), &d, false)
2868            .expect_err("an omitted endpoint is rejected")
2869            .to_string();
2870        assert!(
2871            msg.contains("`b` is missing from"),
2872            "the message should name the omitted endpoint, got: {msg}"
2873        );
2874    }
2875
2876    #[test]
2877    fn an_impl_block_defers_the_unknown_key_check_to_the_const_assertion() {
2878        // The derive cannot see the impl block's endpoints, so an unrecognized
2879        // key here may still be one of them. `assert_listing_order` catches a
2880        // genuine typo at compile time instead; `repe-core`'s
2881        // `const_assertions.rs` pins that message.
2882        let d = declared(&["a"]);
2883        assert!(validate_listing_order(&order(&["a", "calc"]), &d, true).is_ok());
2884
2885        // The other direction is still checked, because a field the derive can
2886        // see is one it knows the order must name.
2887        let msg = validate_listing_order(&order(&["calc"]), &d, true)
2888            .expect_err("a field omitted from the order is still rejected")
2889            .to_string();
2890        assert!(msg.contains("`a` is missing from"), "got: {msg}");
2891    }
2892}