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