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 = ::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 = ::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<::serde_json::Value>,
352                    )
353                },
354                quote! { #repe::structs::StructResult<Option<::serde_json::Value>> },
355            ),
356            Sink::Encode => (
357                quote! {
358                    fn repe_handle_into(
359                        &mut self,
360                        segments: &[&str],
361                        body: Option<::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<::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(self, key: TokenStream2, produce: TokenStream2) -> TokenStream2 {
1179        match self {
1180            ListingSink::Value => quote! {
1181                map.insert(
1182                    String::from(#key),
1183                    (#produce)?.unwrap_or(::serde_json::Value::Null),
1184                );
1185            },
1186            ListingSink::Encode => quote! {
1187                __repe_obj.entry_with(#key, |__repe_nested| { #produce })?;
1188            },
1189            ListingSink::Shared => quote! {
1190                if let Err(__repe_err) = __repe_obj.entry_try_with(#key, |__repe_nested| {
1191                    #produce
1192                })? {
1193                    return Some(Err(__repe_err));
1194                }
1195            },
1196        }
1197    }
1198
1199    /// Write one `"key": value` entry from a value that serializes.
1200    fn entry(
1201        self,
1202        repe: &TokenStream2,
1203        key: TokenStream2,
1204        value: TokenStream2,
1205        path: TokenStream2,
1206    ) -> TokenStream2 {
1207        match self {
1208            ListingSink::Value => quote! {
1209                {
1210                    let __repe_value = ::serde_json::to_value(&#value)
1211                        .map_err(|source| #repe::StructError::Serialize {
1212                            path: String::from(#path),
1213                            source,
1214                        })?;
1215                    map.insert(String::from(#key), __repe_value);
1216                }
1217            },
1218            ListingSink::Encode => quote! { __repe_obj.entry(#key, &#value)?; },
1219            ListingSink::Shared => quote! {
1220                if let Err(__repe_err) = __repe_obj.entry(#key, &#value) {
1221                    return Some(Err(__repe_err));
1222                }
1223            },
1224        }
1225    }
1226
1227    /// Open the body, run `entries`, and close it.
1228    fn wrap(self, entries: &[TokenStream2]) -> TokenStream2 {
1229        match self {
1230            // The `Map` is a `BTreeMap` unless something in the dependency
1231            // graph turns on `serde_json/preserve_order`, so this listing's key
1232            // order is serde_json's and not the derive's — see `build_listing`.
1233            ListingSink::Value => quote! {
1234                {
1235                    let mut map = ::serde_json::Map::new();
1236                    #(#entries)*
1237                    Ok(Some(::serde_json::Value::Object(map)))
1238                }
1239            },
1240            ListingSink::Encode => quote! {
1241                {
1242                    let mut __repe_obj = out.object();
1243                    #(#entries)*
1244                    __repe_obj.finish();
1245                    Ok(())
1246                }
1247            },
1248            ListingSink::Shared => quote! {
1249                {
1250                    let mut __repe_obj = out.object();
1251                    #(#entries)*
1252                    __repe_obj.finish();
1253                    Some(Ok(()))
1254                }
1255            },
1256        }
1257    }
1258}
1259
1260/// The response to a read of the whole struct: every field, plus every method
1261/// published as its signature string.
1262///
1263/// All three listings — the two `Sink` bodies and the shared one — are this one
1264/// walk of one resolved entry list, so they cannot disagree about *what* is
1265/// emitted or in what order.
1266///
1267/// They can still disagree about **key order**, and one of them does: the
1268/// `Value` form assembles a `serde_json::Map`, which is a `BTreeMap` unless
1269/// something in the dependency graph enables `serde_json/preserve_order`, so it
1270/// sorts its keys and can carry neither declaration order nor
1271/// `#[repe(listing_order(..))]`. That is a property of `serde_json::Value` and
1272/// not something this derive can fix; the router calls `repe_handle_into`, so
1273/// the ordering governs every frame that reaches a client.
1274fn build_listing(
1275    entries: &[ListingEntry<'_>],
1276    repe: &TokenStream2,
1277    sink: ListingSink,
1278) -> TokenStream2 {
1279    let mut emitted = Vec::new();
1280
1281    for entry in entries {
1282        emitted.push(match entry {
1283            ListingEntry::Field(field) => {
1284                let key = LitStr::new(&field.endpoint, Span::call_site());
1285                let ident = &field.ident;
1286                if field.attrs.nested {
1287                    // The child writes into a *nested* body, so the frame stays
1288                    // JSON no matter what the child would emit on its own.
1289                    let call = sink.child_call(repe, &field.ty, ident);
1290                    sink.entry_with(
1291                        quote! { #key },
1292                        sink.prepend(repe, call, quote! { #key }),
1293                    )
1294                } else {
1295                    // A `#[repe(nested_serde)]` field lists exactly as a leaf
1296                    // does: the descent it enables is a sub-path concern, and
1297                    // the whole-object shape is what `Serialize` already
1298                    // produces. A `#[repe(typed)]` field is a plain JSON array
1299                    // here, because the enclosing object has already committed
1300                    // the frame to JSON.
1301                    let path = endpoint_path(&field.endpoint);
1302                    sink.entry(repe, quote! { #key }, quote! { self.#ident }, quote! { #path })
1303                }
1304            }
1305            ListingEntry::Signature(method) => {
1306                let key = LitStr::new(&method.endpoint, Span::call_site());
1307                let signature = LitStr::new(&method.signature_display, Span::call_site());
1308                let path = endpoint_path(&method.endpoint);
1309                sink.entry(repe, quote! { #key }, quote! { #signature }, quote! { #path })
1310            }
1311            ListingEntry::ImplNamed(name) => {
1312                let resolved = impl_named_signature(name, repe);
1313                let accessor =
1314                    sink.entry_with(quote! { #name }, sink.accessor_call(repe, quote! { #name }));
1315                let path = endpoint_path(&name.value());
1316                let signature = sink.entry(
1317                    repe,
1318                    quote! { #name },
1319                    quote! { __repe_signature },
1320                    quote! { #path },
1321                );
1322                quote! {
1323                    match #resolved {
1324                        ::core::option::Option::Some(__repe_signature) => { #signature }
1325                        ::core::option::Option::None => { #accessor }
1326                    }
1327                }
1328            }
1329            ListingEntry::ImplSignatures => {
1330                // The endpoint's own name is the error path here; a `&str` has
1331                // no failing `Serialize`, so it is never read.
1332                let entry = sink.entry(repe, quote! { name }, quote! { signature }, quote! { name });
1333                quote! {
1334                    for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
1335                        #entry
1336                    }
1337                }
1338            }
1339            // A field-shaped endpoint is listed the way a field is: by its
1340            // value. The value has to come back through the method table rather
1341            // than from a getter call emitted here, because this derive cannot
1342            // see the impl block and so does not know a single getter's name —
1343            // the endpoint list is all it has. That indirection costs a match
1344            // scan per accessor, so a whole-object read of a struct with many
1345            // accessors is quadratic in the endpoint count; the same read of an
1346            // all-field struct is not.
1347            //
1348            // A getter that returns `Err` fails the whole listing, exactly as a
1349            // field whose `Serialize` impl fails does. That is the field analogy
1350            // held to consistently rather than an oversight, and it is why a
1351            // getter meant to be listed should report a sentinel rather than an
1352            // error.
1353            ListingEntry::ImplAccessors => {
1354                let accessor =
1355                    sink.entry_with(quote! { name }, sink.accessor_call(repe, quote! { name }));
1356                quote! {
1357                    for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
1358                        #accessor
1359                    }
1360                }
1361            }
1362        });
1363    }
1364
1365    sink.wrap(&emitted)
1366}
1367
1368// ---------------------------------------------------------------------------
1369// Field arms
1370// ---------------------------------------------------------------------------
1371
1372/// A call into a `#[repe(nested)]` field's own `RepeStruct` impl, with this
1373/// field's endpoint prefixed onto any error path it produces.
1374fn nested_dispatch(
1375    ty: &Type,
1376    ident: &Ident,
1377    key: LitStr,
1378    args: TokenStream2,
1379    repe: &TokenStream2,
1380    sink: Sink,
1381) -> TokenStream2 {
1382    let method = sink.struct_method();
1383    let args = sink.with_out(quote! { &mut self.#ident, #args });
1384    quote! {
1385        <#ty as #repe::RepeStruct>::#method(#args)
1386            .map_err(|err| #repe::structs::prepend_path(err, #key))
1387    }
1388}
1389
1390fn build_field_arms(fields: &[FieldSpec], repe: &TokenStream2, sink: Sink) -> Vec<TokenStream2> {
1391    let refuse = refuse_write(repe, Raise::Result);
1392    let subpath = refuse_subpath(repe, Raise::Result);
1393    let ack = sink.emit_null();
1394    let mut arms = Vec::new();
1395    for field in fields {
1396        if field.attrs.skip {
1397            continue;
1398        }
1399        let key = LitStr::new(&field.endpoint, Span::call_site());
1400        let ident = &field.ident;
1401        let path = endpoint_path(&field.endpoint);
1402
1403        if field.attrs.nested {
1404            // Reading the child whole differs from writing it by one step in the
1405            // `Value` sink: the child's `Option` has to be lifted into this
1406            // struct's. The encoding sink has already written whatever there was.
1407            let lift = |whole: TokenStream2| match sink {
1408                Sink::Value => quote! {
1409                    {
1410                        let nested = #whole?;
1411                        Ok(Some(nested.unwrap_or(::serde_json::Value::Null)))
1412                    }
1413                },
1414                Sink::Encode => whole,
1415            };
1416
1417            // `readonly` on a nested field refuses every write *through* it,
1418            // subpaths included: the attribute says the field cannot be written,
1419            // and a write below it mutates the field just as surely as a write
1420            // at it. Past this guard `body` is `None`, so the descent below is
1421            // the same code either way.
1422            let guard = field.attrs.readonly.then(|| {
1423                quote! {
1424                    if body.is_some() {
1425                        return #refuse;
1426                    }
1427                }
1428            });
1429
1430            // The whole-child write descends, exactly as the whole-child read
1431            // already did. Before this, a write with an empty tail replaced the
1432            // child — `self.field = from_value(body)?` — and so was the one path
1433            // on which a child's own `RepeStruct` impl was never consulted. That
1434            // is precisely the path where a child backed by a resource has
1435            // something to say: applying a partial object to live state is not
1436            // the same operation as replacing a struct. A derived child's
1437            // empty-segments arm is still `*self = from_value(..)`, so nothing
1438            // that worked before changes; only a hand-written child gains a say.
1439            let descend = nested_dispatch(
1440                &field.ty,
1441                ident,
1442                key.clone(),
1443                quote! { tail, body },
1444                repe,
1445                sink,
1446            );
1447            let body = match sink {
1448                // `tail` *is* the empty slice when it is empty, and `lift` is
1449                // the identity here, so the two branches the `Value` sink needs
1450                // would be the same call twice.
1451                Sink::Encode => quote! { return #descend; },
1452                // Only here do they differ: a whole-child read has to lift the
1453                // child's `Option` into this struct's.
1454                Sink::Value => {
1455                    let whole = lift(nested_dispatch(
1456                        &field.ty,
1457                        ident,
1458                        key.clone(),
1459                        quote! { &[], body },
1460                        repe,
1461                        sink,
1462                    ));
1463                    quote! {
1464                        if tail.is_empty() {
1465                            return #whole;
1466                        }
1467                        return #descend;
1468                    }
1469                }
1470            };
1471            arms.push(quote! { #key => { #guard #body } });
1472        } else if field.attrs.nested_serde {
1473            // Descend by walking a `serde_json::Value` of the field. The whole
1474            // point is that the field's type implements only `Serialize` +
1475            // `DeserializeOwned`, so there is no child impl to ask — which is
1476            // also the cost: a subpath read materializes the field, and a
1477            // subpath write materializes it, edits it, and deserializes it back.
1478            // A whole-field read or write pays neither.
1479            let read = nested_serde_read(field, repe, sink, Raise::Result);
1480            let unresolved = refuse_unresolved(repe, Raise::Result);
1481            let write = if field.attrs.readonly {
1482                quote! { Some(_) => #refuse, }
1483            } else {
1484                quote! {
1485                    Some(value) => {
1486                        if tail.is_empty() {
1487                            self.#ident = ::serde_json::from_value(value)
1488                                .map_err(|source| #repe::StructError::Deserialize {
1489                                    path: String::from(#path),
1490                                    source,
1491                                })?;
1492                            #ack
1493                        } else {
1494                            // The round trip a sub-path write costs, and the
1495                            // reason the field's type has to survive one: the
1496                            // whole child is materialized, edited, and decoded
1497                            // back.
1498                            let mut __repe_value = ::serde_json::to_value(&self.#ident)
1499                                .map_err(|source| #repe::StructError::Serialize {
1500                                    path: String::from(#path),
1501                                    source,
1502                                })?;
1503                            if #repe::structs::serde_pointer_set(&mut __repe_value, tail, value)
1504                                .is_none()
1505                            {
1506                                return #unresolved;
1507                            }
1508                            self.#ident = ::serde_json::from_value(__repe_value)
1509                                .map_err(|source| #repe::StructError::Deserialize {
1510                                    path: String::from(#path),
1511                                    source,
1512                                })?;
1513                            #ack
1514                        }
1515                    }
1516                }
1517            };
1518            arms.push(quote! {
1519                #key => {
1520                    return match body {
1521                        None => { #read }
1522                        #write
1523                    };
1524                }
1525            });
1526        } else {
1527            let read = if field.attrs.typed {
1528                sink.emit_typed_slice(repe, &path, quote! { self.#ident })
1529            } else {
1530                sink.emit_value(repe, &path, quote! { self.#ident })
1531            };
1532            let write = if field.attrs.readonly {
1533                quote! { Some(_) => #refuse, }
1534            } else {
1535                quote! {
1536                    Some(value) => {
1537                        self.#ident = ::serde_json::from_value(value)
1538                            .map_err(|source| #repe::StructError::Deserialize {
1539                                path: String::from(#path),
1540                                source,
1541                            })?;
1542                        #ack
1543                    }
1544                }
1545            };
1546            arms.push(quote! {
1547                #key => {
1548                    if !tail.is_empty() {
1549                        return #subpath;
1550                    }
1551                    return match body {
1552                        None => #read,
1553                        #write
1554                    };
1555                }
1556            });
1557        }
1558    }
1559    arms
1560}
1561
1562// ---------------------------------------------------------------------------
1563// Method arms
1564// ---------------------------------------------------------------------------
1565
1566/// How a generated arm reports a failure.
1567///
1568/// The only difference between the two exclusive dispatch bodies, which return
1569/// `StructResult<..>`, and the shared one, which returns
1570/// `Option<StructResult<()>>` because it may decline. Everything else about
1571/// decoding a method's arguments is identical, so this is what lets one
1572/// generator serve both instead of two that can drift.
1573#[derive(Clone, Copy)]
1574enum Raise {
1575    /// `StructResult<..>`: a failure is `Err`, an answer is bare.
1576    Result,
1577    /// `Option<StructResult<()>>`: everything is wrapped, because `None` is
1578    /// reserved for a decline.
1579    Shared,
1580}
1581
1582impl Raise {
1583    /// `err` as an early return.
1584    fn err(self, err: TokenStream2) -> TokenStream2 {
1585        let refusal = self.refuse(err);
1586        quote! { return #refusal; }
1587    }
1588
1589    /// `err` as an expression in this shape — an answer, not a decline.
1590    fn refuse(self, err: TokenStream2) -> TokenStream2 {
1591        match self {
1592            Raise::Result => quote! { Err(#err) },
1593            Raise::Shared => quote! { Some(Err(#err)) },
1594        }
1595    }
1596
1597    /// A successful `expr` in this shape.
1598    fn ok(self, expr: TokenStream2) -> TokenStream2 {
1599        match self {
1600            Raise::Result => expr,
1601            Raise::Shared => quote! { Some(#expr) },
1602        }
1603    }
1604}
1605
1606/// The refusal a `#[repe(readonly)]` endpoint gives a write.
1607///
1608/// Emitted *instead of* the write, never before it, so a crate building under
1609/// `#![deny(warnings)]` is not broken by an `unreachable_code` lint on generated
1610/// code. Servable under a shared borrow as well as an exclusive one: refusing a
1611/// write touches nothing, so there is no reason to take the write guard to say
1612/// so.
1613fn refuse_write(repe: &TokenStream2, raise: Raise) -> TokenStream2 {
1614    raise.refuse(quote! {
1615        #repe::StructError::BodyUnexpected {
1616            path: #repe::structs::path_from_segments(segments),
1617        }
1618    })
1619}
1620
1621/// The refusal for a path segment below a leaf endpoint.
1622fn refuse_subpath(repe: &TokenStream2, raise: Raise) -> TokenStream2 {
1623    raise.refuse(quote! {
1624        #repe::StructError::InvalidSubpath {
1625            path: #repe::structs::path_from_segments(segments),
1626        }
1627    })
1628}
1629
1630/// The refusal for a path that does not resolve inside a
1631/// `#[repe(nested_serde)]` field.
1632fn refuse_unresolved(repe: &TokenStream2, raise: Raise) -> TokenStream2 {
1633    raise.refuse(quote! {
1634        #repe::StructError::InvalidPath {
1635            path: #repe::structs::path_from_segments(segments),
1636        }
1637    })
1638}
1639
1640/// The read below a `#[repe(nested_serde)]` field, which both borrow paths serve
1641/// identically: serializing the field and walking the result mutates nothing.
1642/// An expression, so it drops into the exclusive arm's `match body` and the
1643/// shared arm's tail position unchanged.
1644fn nested_serde_read(
1645    field: &FieldSpec,
1646    repe: &TokenStream2,
1647    sink: Sink,
1648    raise: Raise,
1649) -> TokenStream2 {
1650    let ident = &field.ident;
1651    let path = endpoint_path(&field.endpoint);
1652    let whole = raise.ok(sink.emit_value(repe, &path, quote! { self.#ident }));
1653    let found = raise.ok(sink.emit_value(repe, &path, quote! { __repe_found }));
1654    let unresolved = refuse_unresolved(repe, raise);
1655    let unserializable = raise.refuse(quote! {
1656        #repe::StructError::Serialize {
1657            path: String::from(#path),
1658            source,
1659        }
1660    });
1661    quote! {
1662        if tail.is_empty() {
1663            #whole
1664        } else {
1665            match ::serde_json::to_value(&self.#ident) {
1666                Ok(__repe_value) => match #repe::structs::serde_pointer(&__repe_value, tail) {
1667                    Some(__repe_found) => #found,
1668                    None => #unresolved,
1669                },
1670                Err(source) => #unserializable,
1671            }
1672        }
1673    }
1674}
1675
1676/// Bind a published method's arguments out of the request body.
1677///
1678/// One argument *is* the body — the shape the wire has always had. Two or more
1679/// arrive as a positional array or a name-keyed object; see `MethodArgs`. A
1680/// method taking none ignores whatever the body holds, which is what makes it
1681/// callable from a bodiless frame.
1682fn decode_method_args(
1683    method: &MethodSpec,
1684    bindings: &[Ident],
1685    repe: &TokenStream2,
1686    raise: Raise,
1687) -> TokenStream2 {
1688    if method.args.is_empty() {
1689        return quote! { let _ = &body; };
1690    }
1691    let path = endpoint_path(&method.endpoint);
1692    let missing = raise.err(quote! {
1693        #repe::StructError::BodyExpected {
1694            path: #repe::structs::path_from_segments(segments),
1695        }
1696    });
1697    let take_body = match raise {
1698        Raise::Result => quote! {
1699            let value = match body {
1700                Some(value) => value,
1701                None => { #missing }
1702            };
1703        },
1704        // Taken here and nowhere earlier: past this point the arm answers, so
1705        // the body can no longer be owed back to the exclusive retry.
1706        Raise::Shared => quote! {
1707            let value = match body.take() {
1708                Some(value) => value,
1709                None => { #missing }
1710            };
1711        },
1712    };
1713
1714    if method.args.len() == 1 {
1715        let binding = &bindings[0];
1716        let ty = &method.args[0].1;
1717        let undecodable = raise.err(quote! {
1718            #repe::StructError::Deserialize {
1719                path: String::from(#path),
1720                source,
1721            }
1722        });
1723        return quote! {
1724            #take_body
1725            let #binding: #ty = match ::serde_json::from_value(value) {
1726                Ok(__repe_value) => __repe_value,
1727                Err(source) => { #undecodable }
1728            };
1729        };
1730    }
1731
1732    let names: Vec<LitStr> = method
1733        .args
1734        .iter()
1735        .map(|(ident, _)| LitStr::new(&ident.to_string(), Span::call_site()))
1736        .collect();
1737    let bad_args = raise.err(quote! { __repe_err });
1738    let decls = method.args.iter().zip(bindings).map(|((_, ty), binding)| {
1739        let bad_args = bad_args.clone();
1740        quote! {
1741            let #binding: #ty = match __repe_args.next_arg() {
1742                Ok(__repe_value) => __repe_value,
1743                Err(__repe_err) => { #bad_args }
1744            };
1745        }
1746    });
1747    quote! {
1748        #take_body
1749        let mut __repe_args = match #repe::structs::MethodArgs::new(#path, &[#(#names),*], value) {
1750            Ok(__repe_args) => __repe_args,
1751            Err(__repe_err) => { #bad_args }
1752        };
1753        #(#decls)*
1754    }
1755}
1756
1757fn build_method_arms(
1758    methods: &[MethodSpec],
1759    repe: &TokenStream2,
1760    sink: Sink,
1761    raise: Raise,
1762) -> Vec<TokenStream2> {
1763    methods
1764        .iter()
1765        .map(|method| build_method_arm(method, repe, sink, raise))
1766        .collect()
1767}
1768
1769fn build_method_arm(
1770    method: &MethodSpec,
1771    repe: &TokenStream2,
1772    sink: Sink,
1773    raise: Raise,
1774) -> TokenStream2 {
1775    let key = LitStr::new(&method.endpoint, Span::call_site());
1776    // A `&mut self` method cannot run under a shared borrow however the frame is
1777    // shaped. Declining costs nothing: the exclusive path answers it exactly as
1778    // it always has.
1779    if matches!(raise, Raise::Shared) && !matches!(method.receiver, ReceiverKind::Ref) {
1780        return quote! { #key => None, };
1781    }
1782    let path = endpoint_path(&method.endpoint);
1783    let subpath = refuse_subpath(repe, raise);
1784    let method_ident = &method.method_ident;
1785
1786    let bindings: Vec<Ident> = (0..method.args.len())
1787        .map(|i| format_ident!("__repe_arg{}", i))
1788        .collect();
1789
1790    let decode_args = decode_method_args(method, &bindings, repe, raise);
1791
1792    let emit_ok = if method.ret.ok_is_unit() {
1793        sink.emit_null()
1794    } else {
1795        sink.emit_value(repe, &path, quote! { __repe_ok })
1796    };
1797    // Spanned at the method name, because this is the one call in the generated
1798    // code whose receiver comes from a *declaration* rather than from a
1799    // signature: a `#[repe(methods(..))]` entry that says `&self` for a
1800    // `&mut self` method fails here, and the error has to point at that entry
1801    // rather than at `#[derive(RepeStruct)]`.
1802    let invocation = quote_spanned! { method_ident.span()=>
1803        Self::#method_ident(self #(, #bindings)*)
1804    };
1805    let call = raise.ok(call_and_emit(invocation, &method.ret, emit_ok, repe, &path));
1806
1807    quote! {
1808        #key => {
1809            if !tail.is_empty() {
1810                return #subpath;
1811            }
1812            #decode_args
1813            #call
1814        }
1815    }
1816}
1817
1818/// Call a published method and turn what it returned into a response.
1819///
1820/// `emit_ok` is the response for a success, written against a binding named
1821/// `__repe_ok` when the `Ok` type is not `()`. A declared `Result` turns `Err`
1822/// into a [`StructError::Execution`] naming `path`, rather than serializing the
1823/// `Result` itself.
1824///
1825/// Shared by the method arms and by both halves of an accessor pair, so a
1826/// getter that fails reports it exactly as a method that fails does.
1827fn call_and_emit(
1828    invocation: TokenStream2,
1829    ret: &ReturnSpec,
1830    emit_ok: TokenStream2,
1831    repe: &TokenStream2,
1832    path: &LitStr,
1833) -> TokenStream2 {
1834    if ret.fallible {
1835        let ok_pattern = if ret.ok_is_unit() {
1836            quote! { Ok(_) }
1837        } else {
1838            quote! { Ok(__repe_ok) }
1839        };
1840        quote! {
1841            match #invocation {
1842                #ok_pattern => #emit_ok,
1843                Err(__repe_err) => Err(#repe::StructError::Execution {
1844                    path: String::from(#path),
1845                    message: ::std::string::ToString::to_string(&__repe_err),
1846                }),
1847            }
1848        }
1849    } else if ret.ok_is_unit() {
1850        // Braced so every branch is an *expression*, usable as a match arm body
1851        // as well as a statement tail.
1852        quote! {
1853            {
1854                #invocation;
1855                #emit_ok
1856            }
1857        }
1858    } else {
1859        quote! {
1860            {
1861                let __repe_ok = #invocation;
1862                #emit_ok
1863            }
1864        }
1865    }
1866}
1867
1868// ---------------------------------------------------------------------------
1869// Accessor arms
1870// ---------------------------------------------------------------------------
1871
1872/// One dispatch arm for a field-shaped endpoint, shaped exactly like the arm
1873/// [`build_field_arms`] emits for a real field: no body reads, a body writes,
1874/// and a trailing path segment is a `InvalidSubpath` either way.
1875///
1876/// The only difference is where the value comes from — a getter call instead of
1877/// a field read, a setter call instead of an assignment — which is the whole
1878/// point of the attribute.
1879fn build_accessor_arm(
1880    accessor: &AccessorSpec,
1881    repe: &TokenStream2,
1882    sink: Sink,
1883    raise: Raise,
1884) -> TokenStream2 {
1885    let key = LitStr::new(&accessor.endpoint, Span::call_site());
1886    let path = endpoint_path(&accessor.endpoint);
1887    let subpath = refuse_subpath(repe, raise);
1888
1889    // No `ok_is_unit` branch: a getter that returns nothing is rejected at
1890    // `parse_impl_method`, since the listing would have no value to show for the
1891    // endpoint. A `&mut self` getter cannot run under a shared borrow.
1892    let read =
1893        if matches!(raise, Raise::Shared) && !matches!(accessor.get.receiver, ReceiverKind::Ref) {
1894            quote! { None }
1895        } else {
1896            let getter = &accessor.get.method_ident;
1897            let emit = if accessor.typed {
1898                sink.emit_typed_slice(repe, &path, quote! { __repe_ok })
1899            } else {
1900                sink.emit_value(repe, &path, quote! { __repe_ok })
1901            };
1902            raise.ok(call_and_emit(
1903                quote! { Self::#getter(self) },
1904                &accessor.get.ret,
1905                emit,
1906                repe,
1907                &path,
1908            ))
1909        };
1910
1911    // A getter with no setter *is* a read-only endpoint, so the refusal is the
1912    // same one `#[repe(readonly)]` produces on a field. Emitting only the
1913    // rejection — never a write followed by dead code — keeps generated code
1914    // clean under `#![deny(warnings)]`, as the field arms do. A setter mutates
1915    // by construction, so the shared borrow declines it; the refusal above
1916    // mutates nothing and is served either way.
1917    let refuse = refuse_write(repe, raise);
1918    let write = match (&accessor.set, raise) {
1919        (None, _) => quote! { Some(_) => #refuse, },
1920        (Some(_), Raise::Shared) => quote! { Some(_) => None, },
1921        (Some(set), Raise::Result) => {
1922            let setter = &set.method_ident;
1923            let ty = &set.args[0].1;
1924            let call = call_and_emit(
1925                quote! { Self::#setter(self, __repe_arg) },
1926                &set.ret,
1927                sink.emit_null(),
1928                repe,
1929                &path,
1930            );
1931            quote! {
1932                Some(value) => {
1933                    let __repe_arg: #ty = ::serde_json::from_value(value)
1934                        .map_err(|source| #repe::StructError::Deserialize {
1935                            path: String::from(#path),
1936                            source,
1937                        })?;
1938                    #call
1939                }
1940            }
1941        }
1942    };
1943
1944    quote! {
1945        #key => {
1946            if !tail.is_empty() {
1947                return #subpath;
1948            }
1949            match body {
1950                None => #read,
1951                #write
1952            }
1953        }
1954    }
1955}
1956
1957// ---------------------------------------------------------------------------
1958// Shared-borrow path
1959// ---------------------------------------------------------------------------
1960//
1961// `repe_shared_into` and `repe_call_shared_into` serve a request through
1962// `&self`, so a read does not queue behind a long-running call on the same
1963// object. A decline is not a value any sink can encode, so this is not a third
1964// `Sink`; it is a second `Raise`, and the arms themselves are the same
1965// generators the exclusive path uses — `build_method_arm`, `build_accessor_arm`
1966// — called with `Raise::Shared`.
1967//
1968// That is why the two cannot disagree about how a value is serialized or how a
1969// body is read: it is one generator, not two kept in step. They differ only in
1970// whether this borrow serves a path at all, which is decided from the receiver
1971// at the top of each arm. `tests/shared_reads.rs` pins the rest by driving one
1972// struct through both and comparing frames.
1973//
1974// The field and listing arms are still built separately, because there the
1975// shapes genuinely diverge: a nested child is asked to decline in turn, and a
1976// listing rewinds.
1977//
1978// **What decides.** The receiver, not the frame. REPE separates read from write
1979// at the frame level, and taking that as the borrow rule meant a `&self` method
1980// carrying arguments — a long computation, an HTTP fetch, a system call — ran
1981// under the write guard and stalled every read of the object for its duration. That is
1982// the receiver being known at expansion and thrown away. So: a `&self` method is
1983// served here whether or not it carries a body, a `&mut self` one never is, a
1984// field write never is, and a nested child is asked the same question in turn.
1985//
1986// **The body.** It arrives as `&mut Option<Value>` and is taken only past the
1987// last point an arm could still decline, because a decline owes the exclusive
1988// retry the request it was handed. `decode_method_args` places the `take` for
1989// that reason; a nested child is passed the borrow directly and holds the same
1990// obligation.
1991//
1992// **Listings settle first.** A listing is the one read that composes many
1993// others, so a decline discovered partway through would leave the entries before
1994// it already executed, and the exclusive retry executes them again — a `&self`
1995// getter over a read counter would report the second call. Rewinding the
1996// response buffer undoes the bytes; it cannot undo a call. Two things can force
1997// that decline, and the guard asks about both: an accessor on this struct whose
1998// getter takes `&mut self`, and a `#[repe(nested)]` child that declines at any
1999// depth. `listing_decline_terms` builds the question;
2000// `RepeStruct::repe_listing_declines` is how a parent asks it of a child. Once
2001// the guard passes, nothing left in the listing can decline.
2002//
2003// Reading one of those endpoints on its own is unaffected: that arm decides from
2004// the receiver, before it calls anything.
2005
2006/// One shared arm per field: a leaf serializes itself, a nested field asks its
2007/// child, which may decline in turn, and a write declines unless the field is
2008/// read-only.
2009fn build_shared_field_arms(fields: &[FieldSpec], repe: &TokenStream2) -> Vec<TokenStream2> {
2010    let subpath = refuse_subpath(repe, Raise::Shared);
2011    let refuse = refuse_write(repe, Raise::Shared);
2012    let mut arms = Vec::new();
2013    for field in fields {
2014        if field.attrs.skip {
2015            continue;
2016        }
2017        let key = LitStr::new(&field.endpoint, Span::call_site());
2018        let ident = &field.ident;
2019        let path = endpoint_path(&field.endpoint);
2020        // A write needs `&mut self` unless it is refused outright, in which case
2021        // it needs nothing at all.
2022        let write = if field.attrs.readonly {
2023            refuse.clone()
2024        } else {
2025            quote! { None }
2026        };
2027
2028        if field.attrs.nested {
2029            // `tail` covers both cases the exclusive path splits: empty asks the
2030            // child whole, non-empty descends. The child is handed the body
2031            // borrow and the same obligation to leave it alone if it declines.
2032            let ty = &field.ty;
2033            let forward = quote! {
2034                <#ty as #repe::RepeStruct>::repe_shared_into(&self.#ident, tail, body, out)
2035                    .map(|__repe_result| {
2036                        __repe_result.map_err(|err| #repe::structs::prepend_path(err, #key))
2037                    })
2038            };
2039            if field.attrs.readonly {
2040                arms.push(quote! {
2041                    #key => {
2042                        if body.is_some() {
2043                            return #refuse;
2044                        }
2045                        #forward
2046                    }
2047                });
2048            } else {
2049                arms.push(quote! { #key => #forward, });
2050            }
2051        } else if field.attrs.nested_serde {
2052            // Every read below the field is `&self`: serializing the field and
2053            // walking the result mutates nothing, so the whole descent is
2054            // servable here, through the same generator the exclusive arm uses.
2055            // A write is a write.
2056            let read = nested_serde_read(field, repe, Sink::Encode, Raise::Shared);
2057            arms.push(quote! {
2058                #key => {
2059                    if body.is_some() {
2060                        return #write;
2061                    }
2062                    #read
2063                }
2064            });
2065        } else {
2066            let read = if field.attrs.typed {
2067                Sink::Encode.emit_typed_slice(repe, &path, quote! { self.#ident })
2068            } else {
2069                Sink::Encode.emit_value(repe, &path, quote! { self.#ident })
2070            };
2071            arms.push(quote! {
2072                #key => {
2073                    if !tail.is_empty() {
2074                        return #subpath;
2075                    }
2076                    if body.is_some() {
2077                        return #write;
2078                    }
2079                    Some(#read)
2080                }
2081            });
2082        }
2083    }
2084    arms
2085}
2086
2087/// The terms of "a shared whole-object listing of this struct declines",
2088/// OR'd together by both places that need the answer: the guard at the top of
2089/// the listing, and the `RepeStruct::repe_listing_declines` this struct
2090/// publishes for any parent that nests it.
2091///
2092/// Two things can force a listing exclusive, and they are not the same thing:
2093///
2094/// * an accessor on **this** struct whose getter takes `&mut self`, which
2095///   `#[repe::methods]` reports as `REPE_LISTING_NEEDS_EXCLUSIVE`; and
2096/// * a `#[repe(nested)]` child that declines, at any depth — the parent's
2097///   listing composes the child's, so the child's refusal is the parent's.
2098///
2099/// The second is why this cannot be read off `RepeMethods` alone. A child is
2100/// listed *before* this struct's own accessors are read, so a child discovered
2101/// to decline partway through would leave those already invoked — and the
2102/// exclusive retry invokes them again. Asking every child up front is what makes
2103/// the guard's promise ("nothing after this point can decline") true rather than
2104/// true by accident of declaration order.
2105///
2106/// A `#[repe(nested_serde)]` field contributes no term: it is listed by
2107/// `Serialize`, exactly as a leaf is, and has no impl of its own to ask.
2108///
2109/// An empty result means the constant `false`: a struct of plain fields, or one
2110/// whose nesting and accessors all read shared. The caller emits no guard at all
2111/// for that, so the common case costs nothing.
2112/// The terms of "some path on this struct answers a body-carrying frame under a
2113/// shared borrow", OR'd into the `RepeStruct::REPE_SHARED_SERVES_BODIES` this
2114/// struct publishes.
2115///
2116/// The const is a hint the router reads before it takes the read lock, so the
2117/// only cost of a wrong answer is concurrency: everything the shared borrow
2118/// answers with a body, the exclusive path answers identically. That makes `true`
2119/// the safe direction, and this over-approximates deliberately rather than
2120/// tracking every arm shape exactly.
2121///
2122/// Four things put a body-carrying answer on this struct:
2123///
2124/// * `#[repe(readonly)]` on the struct, whose whole-object refusal is servable
2125///   shared — there is no reason to take the write guard to say no;
2126/// * `#[repe(readonly)]` on a field, for the same reason one level down;
2127/// * a struct-listed `&self` method that takes arguments, which is a call
2128///   rather than a mutation and is exactly what the shared path exists for; and
2129/// * a `#[repe(nested)]` child with any of the above, at any depth.
2130///
2131/// The impl block's own methods and accessors are a fifth, but the derive
2132/// cannot see them; `#[repe::methods]` computes
2133/// `RepeMethods::REPE_SHARED_SERVES_BODIES` and this ORs it in.
2134///
2135/// A `#[repe(nested_serde)]` field contributes no term unless it is read-only:
2136/// it is walked through `serde`, and a write through it needs `&mut self`.
2137///
2138/// An empty result means the constant `false` — a struct of plain fields whose
2139/// every write needs the exclusive borrow, which is the shape the skip is for.
2140fn shared_body_terms(
2141    fields: &[FieldSpec],
2142    struct_attrs: &StructAttrs,
2143    from_impl_block: bool,
2144    repe: &TokenStream2,
2145) -> Vec<TokenStream2> {
2146    // A refusal that needs no state, or a call that needs no mutation: both are
2147    // answers this struct can give without the write guard.
2148    if struct_attrs.no_replace
2149        || struct_attrs
2150            .methods
2151            .iter()
2152            .any(|m| matches!(m.receiver, ReceiverKind::Ref) && !m.args.is_empty())
2153    {
2154        return vec![quote! { true }];
2155    }
2156
2157    let mut terms = Vec::new();
2158    if from_impl_block {
2159        terms.push(quote! {
2160            <Self as #repe::structs::RepeMethods>::REPE_SHARED_SERVES_BODIES
2161        });
2162    }
2163    for field in fields {
2164        if field.attrs.skip {
2165            continue;
2166        }
2167        if field.attrs.readonly {
2168            return vec![quote! { true }];
2169        }
2170        if !field.attrs.nested {
2171            continue;
2172        }
2173        let ty = &field.ty;
2174        terms.push(quote! {
2175            <#ty as #repe::RepeStruct>::REPE_SHARED_SERVES_BODIES
2176        });
2177    }
2178    terms
2179}
2180
2181fn listing_decline_terms(
2182    fields: &[FieldSpec],
2183    from_impl_block: bool,
2184    repe: &TokenStream2,
2185) -> Vec<TokenStream2> {
2186    let mut terms = Vec::new();
2187    if from_impl_block {
2188        terms.push(quote! {
2189            <Self as #repe::structs::RepeMethods>::REPE_LISTING_NEEDS_EXCLUSIVE
2190        });
2191    }
2192    for field in fields {
2193        if field.attrs.skip || !field.attrs.nested {
2194            continue;
2195        }
2196        let ident = &field.ident;
2197        let ty = &field.ty;
2198        terms.push(quote! {
2199            <#ty as #repe::RepeStruct>::repe_listing_declines(&self.#ident)
2200        });
2201    }
2202    terms
2203}
2204
2205// ---------------------------------------------------------------------------
2206// #[repe::methods]
2207// ---------------------------------------------------------------------------
2208
2209fn expand_methods(mut item_impl: ItemImpl) -> TokenStream2 {
2210    let repe = repe_crate_path();
2211    // Strip our attributes before anything can fail, so the impl block is
2212    // re-emittable either way — `repe` is not a registered attribute on a plain
2213    // inherent impl, and leaving one behind would bury the real error.
2214    let mut stripped = Vec::new();
2215    for item in &mut item_impl.items {
2216        if let ImplItem::Fn(func) = item {
2217            stripped.push(take_method_attrs(&mut func.attrs));
2218        }
2219    }
2220
2221    match collect_methods(&item_impl, stripped) {
2222        Ok(published) => methods_impl(&item_impl, &published, &repe, false),
2223        Err(err) => {
2224            // Emit the diagnostic *and* a table with nothing in it, marked as
2225            // the recovery shape. Failing with the error alone would drop the
2226            // `RepeMethods` impl and add a second, misleading "no
2227            // `#[repe::methods]` impl block" error on top of the real one; the
2228            // marker is what lets the compile-time checks against these tables
2229            // stand down without also standing down for a block that compiles
2230            // and happens to publish nothing.
2231            let error = err.to_compile_error();
2232            let empty = methods_impl(&item_impl, &PublishedItems::default(), &repe, true);
2233            quote! {
2234                #error
2235                #empty
2236            }
2237        }
2238    }
2239}
2240
2241/// Which of the three published shapes one signature in a `#[repe::methods]`
2242/// block takes.
2243enum Published {
2244    /// An ordinary endpoint: the request body carries the arguments.
2245    Method,
2246    /// The read half of a field-shaped endpoint, carrying whether the getter
2247    /// asked for the BEVE typed-slice encoding.
2248    Get { typed: bool },
2249    /// The write half of a field-shaped endpoint.
2250    Set,
2251}
2252
2253/// A **field-shaped endpoint** backed by a getter/setter pair.
2254///
2255/// The wire shape is a field's — a bodiless request reads it, a request with a
2256/// body writes it, and the whole-struct listing shows its value — while the
2257/// implementation is two methods. That is the one endpoint shape a struct
2258/// cannot express by naming a field: a value that is derived, unit-converted,
2259/// or backed by a resource rather than by storage.
2260struct AccessorSpec {
2261    endpoint: String,
2262    /// The read half. Every accessor has one: without it the whole-struct
2263    /// listing would have no value to show for the endpoint.
2264    get: MethodSpec,
2265    /// `#[repe(typed)]` on the getter: encode the value as a BEVE typed numeric
2266    /// array, exactly as the field attribute of the same name does.
2267    typed: bool,
2268    /// The write half, absent for a read-only accessor — which is how a
2269    /// read-only field-shaped endpoint is spelled: there is no setter to call,
2270    /// so a write is refused the way `#[repe(readonly)]` refuses one.
2271    set: Option<MethodSpec>,
2272}
2273
2274/// Everything one `#[repe::methods]` block publishes.
2275#[derive(Default)]
2276struct PublishedItems {
2277    methods: Vec<MethodSpec>,
2278    accessors: Vec<AccessorSpec>,
2279}
2280
2281/// Reject two `#[repe(get = "x")]` methods, or two `#[repe(set = "x")]` methods,
2282/// claiming one endpoint.
2283///
2284/// Separate from [`reject_duplicate_endpoints`] only for the remedy: that one
2285/// recommends `#[repe(rename = "...")]`, which is itself a hard error on an
2286/// accessor half.
2287fn reject_duplicate_accessor_half<'a>(
2288    halves: &(impl Iterator<Item = &'a MethodSpec> + Clone),
2289    key: &str,
2290) -> syn::Result<()> {
2291    let mut seen: Vec<&str> = Vec::new();
2292    for spec in halves.clone() {
2293        if seen.contains(&spec.endpoint.as_str()) {
2294            return Err(syn::Error::new(
2295                spec.method_ident.span(),
2296                format!(
2297                    "two methods claim `#[repe({key} = \"{endpoint}\")]`; a field-shaped \
2298                     endpoint has one read half and one write half, so one of these could never \
2299                     be called. Give one of them a different endpoint.",
2300                    endpoint = spec.endpoint
2301                ),
2302            ));
2303        }
2304        seen.push(&spec.endpoint);
2305    }
2306    Ok(())
2307}
2308
2309/// Validate every method in the block and collect what will be published.
2310fn collect_methods(
2311    item_impl: &ItemImpl,
2312    stripped: Vec<syn::Result<MethodAttrs>>,
2313) -> syn::Result<PublishedItems> {
2314    if let Some((_, path, _)) = &item_impl.trait_ {
2315        return Err(syn::Error::new_spanned(
2316            path,
2317            "`#[repe::methods]` applies to an inherent impl block, not a trait impl",
2318        ));
2319    }
2320
2321    let mut methods: Vec<MethodSpec> = Vec::new();
2322    // Halves arrive in source order and are paired afterwards, so the two halves
2323    // of one endpoint need not sit next to each other.
2324    let mut getters: Vec<(MethodSpec, bool)> = Vec::new();
2325    let mut setters: Vec<MethodSpec> = Vec::new();
2326    let mut stripped = stripped.into_iter();
2327    for item in &item_impl.items {
2328        let ImplItem::Fn(func) = item else {
2329            continue;
2330        };
2331        let attrs = stripped
2332            .next()
2333            .expect("one parsed attribute set per impl fn")?;
2334        if attrs.skip {
2335            continue;
2336        }
2337        let Some((published, spec)) = parse_impl_method(&func.sig, &func.attrs, attrs)? else {
2338            continue;
2339        };
2340        match published {
2341            Published::Method => methods.push(spec),
2342            Published::Get { typed } => getters.push((spec, typed)),
2343            Published::Set => setters.push(spec),
2344        }
2345    }
2346
2347    // Each half is checked on its own, with its own message: the generic
2348    // duplicate-endpoint error recommends `#[repe(rename = "...")]`, which is a
2349    // hard error on an accessor half, so it would send the reader somewhere the
2350    // macro refuses to follow.
2351    reject_duplicate_accessor_half(&getters.iter().map(|(spec, _)| spec), "get")?;
2352    reject_duplicate_accessor_half(&setters.iter(), "set")?;
2353
2354    let mut accessors: Vec<AccessorSpec> = Vec::new();
2355    for (get, typed) in getters {
2356        let set = setters
2357            .iter()
2358            .position(|spec| spec.endpoint == get.endpoint)
2359            .map(|index| setters.remove(index));
2360        accessors.push(AccessorSpec {
2361            endpoint: get.endpoint.clone(),
2362            get,
2363            typed,
2364            set,
2365        });
2366    }
2367    // A setter with no getter left over. Publishing it would give the endpoint a
2368    // value the listing cannot show and a client cannot read back, so the shape
2369    // is refused rather than half-served.
2370    if let Some(orphan) = setters.first() {
2371        return Err(syn::Error::new(
2372            orphan.method_ident.span(),
2373            format!(
2374                "`#[repe(set = \"{endpoint}\")]` has no matching \
2375                 `#[repe(get = \"{endpoint}\")]` in this block: a field-shaped endpoint that \
2376                 cannot be read has no value for the whole-struct listing to show. Add the read \
2377                 half, or publish this as an ordinary method.",
2378                endpoint = orphan.endpoint
2379            ),
2380        ));
2381    }
2382
2383    let endpoints: Vec<(&str, Span)> = methods
2384        .iter()
2385        .map(|spec| (spec.endpoint.as_str(), spec.method_ident.span()))
2386        .chain(
2387            accessors
2388                .iter()
2389                .map(|spec| (spec.endpoint.as_str(), spec.get.method_ident.span())),
2390        )
2391        .collect();
2392    reject_duplicate_endpoints(&endpoints)?;
2393    Ok(PublishedItems { methods, accessors })
2394}
2395
2396/// The impl block itself plus the `RepeMethods` table for `published`.
2397fn methods_impl(
2398    item_impl: &ItemImpl,
2399    published: &PublishedItems,
2400    repe: &TokenStream2,
2401    recovered: bool,
2402) -> TokenStream2 {
2403    let self_ty = &item_impl.self_ty;
2404    let (impl_generics, _ty_generics, where_clause) = item_impl.generics.split_for_impl();
2405
2406    let signatures = published.methods.iter().map(|spec| {
2407        let endpoint = LitStr::new(&spec.endpoint, Span::call_site());
2408        let signature = LitStr::new(&spec.signature_display, Span::call_site());
2409        quote! { (#endpoint, #signature) }
2410    });
2411    let accessor_endpoints = published
2412        .accessors
2413        .iter()
2414        .map(|spec| LitStr::new(&spec.endpoint, Span::call_site()));
2415    // The shared whole-struct listing reads every accessor back through
2416    // `repe_call_shared_into`, which serves a getter only when it takes `&self`.
2417    // One `&mut self` getter is enough to make a decline possible partway
2418    // through the listing, and a decline discovered there would leave the
2419    // getters before it invoked twice — so the listing declines at the top
2420    // instead. Every getter being `&self` means no entry can decline, which is
2421    // what lets the listing be served shared.
2422    let listing_needs_exclusive = published
2423        .accessors
2424        .iter()
2425        .any(|spec| !matches!(spec.get.receiver, ReceiverKind::Ref));
2426
2427    // Which endpoints in this table answer a frame that carries a body without
2428    // the exclusive borrow: a `&self` method taking arguments (a call, not a
2429    // mutation), a `&self` setter, and a read-only accessor, whose refusal
2430    // needs no state to give. Everything else declines, and the router can skip
2431    // the attempt when nothing here is any of the three.
2432    let shared_serves_bodies = published
2433        .methods
2434        .iter()
2435        .any(|spec| matches!(spec.receiver, ReceiverKind::Ref) && !spec.args.is_empty())
2436        || published.accessors.iter().any(|spec| match &spec.set {
2437            Some(set) => matches!(set.receiver, ReceiverKind::Ref),
2438            None => true,
2439        });
2440
2441    let mut bodies = Vec::new();
2442    for sink in [Sink::Value, Sink::Encode] {
2443        let arms = build_method_arms(&published.methods, repe, sink, Raise::Result)
2444            .into_iter()
2445            .chain(
2446                published
2447                    .accessors
2448                    .iter()
2449                    .map(|accessor| build_accessor_arm(accessor, repe, sink, Raise::Result)),
2450            )
2451            .collect::<Vec<_>>();
2452        let (signature, ret, unused) = match sink {
2453            Sink::Value => (
2454                quote! {
2455                    fn repe_call(
2456                        &mut self,
2457                        segments: &[&str],
2458                        body: Option<::serde_json::Value>,
2459                    )
2460                },
2461                quote! { #repe::structs::StructResult<Option<::serde_json::Value>> },
2462                quote! { let _ = &body; },
2463            ),
2464            Sink::Encode => (
2465                quote! {
2466                    fn repe_call_into(
2467                        &mut self,
2468                        segments: &[&str],
2469                        body: Option<::serde_json::Value>,
2470                        out: &mut #repe::structs::ResponseBody<'_>,
2471                    )
2472                },
2473                quote! { #repe::structs::StructResult<()> },
2474                quote! { let _ = &body; let _ = &out; },
2475            ),
2476        };
2477        bodies.push(quote! {
2478            #signature -> #ret {
2479                let Some((head, tail)) = segments.split_first() else {
2480                    return Err(#repe::StructError::InvalidPath { path: String::from("") });
2481                };
2482                #unused
2483                match *head {
2484                    #(#arms)*
2485                    _ => Err(#repe::StructError::InvalidPath {
2486                        path: #repe::structs::path_from_segments(segments),
2487                    }),
2488                }
2489            }
2490        });
2491    }
2492
2493    let shared_arms = build_method_arms(&published.methods, repe, Sink::Encode, Raise::Shared)
2494        .into_iter()
2495        .chain(
2496            published
2497                .accessors
2498                .iter()
2499                .map(|accessor| build_accessor_arm(accessor, repe, Sink::Encode, Raise::Shared)),
2500        )
2501        .collect::<Vec<_>>();
2502    let shared_invalid_root = quote! {
2503        Some(Err(#repe::StructError::InvalidPath { path: String::from("") }))
2504    };
2505    let shared_invalid_path = quote! {
2506        Some(Err(#repe::StructError::InvalidPath {
2507            path: #repe::structs::path_from_segments(segments),
2508        }))
2509    };
2510    bodies.push(quote! {
2511        fn repe_call_shared_into(
2512            &self,
2513            segments: &[&str],
2514            body: &mut Option<::serde_json::Value>,
2515            out: &mut #repe::structs::ResponseBody<'_>,
2516        ) -> Option<#repe::structs::StructResult<()>> {
2517            let Some((head, tail)) = segments.split_first() else {
2518                return #shared_invalid_root;
2519            };
2520            // Every arm may be a decline, in which case none of these is read.
2521            let _ = (&out, tail, &body);
2522            match *head {
2523                #(#shared_arms)*
2524                _ => #shared_invalid_path,
2525            }
2526        }
2527    });
2528
2529    // No handshake assertion to emit: `MethodsDeclared` is a supertrait of
2530    // `RepeMethods`, so this impl cannot compile unless the struct declared
2531    // `#[repe(methods)]`.
2532    quote! {
2533        #item_impl
2534
2535        impl #impl_generics #repe::structs::RepeMethods for #self_ty #where_clause {
2536            const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)] =
2537                &[#(#signatures),*];
2538
2539            const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] =
2540                &[#(#accessor_endpoints),*];
2541
2542            const REPE_LISTING_NEEDS_EXCLUSIVE: bool = #listing_needs_exclusive;
2543
2544            const REPE_SHARED_SERVES_BODIES: bool = #shared_serves_bodies;
2545
2546            const REPE_TABLE_RECOVERED: bool = #recovered;
2547
2548            #(#bodies)*
2549        }
2550    }
2551}
2552
2553#[derive(Default)]
2554struct MethodAttrs {
2555    rename: Option<String>,
2556    skip: bool,
2557    /// `#[repe(get = "endpoint")]`: this method is the read half of the
2558    /// field-shaped endpoint it names.
2559    get: Option<LitStr>,
2560    /// `#[repe(set = "endpoint")]`: this method is the write half.
2561    set: Option<LitStr>,
2562    /// `#[repe(typed)]` on a getter, the accessor twin of the field attribute.
2563    /// Carries its own span, which is the only one an error about it can point
2564    /// at when there is no `get`/`set` literal to blame.
2565    typed: Option<Span>,
2566}
2567
2568impl MethodAttrs {
2569    /// The endpoint this method serves as an accessor half, if it is one.
2570    fn accessor_endpoint(&self) -> Option<&LitStr> {
2571        self.get.as_ref().or(self.set.as_ref())
2572    }
2573}
2574
2575/// Read the `#[repe(..)]` attributes off a method in a `#[repe::methods]` block
2576/// and strip them, since the inherent impl is re-emitted verbatim and `repe` is
2577/// not a registered attribute there.
2578fn take_method_attrs(attrs: &mut Vec<Attribute>) -> syn::Result<MethodAttrs> {
2579    let mut parsed = MethodAttrs::default();
2580    for attr in attrs.iter() {
2581        if !attr.path().is_ident("repe") {
2582            continue;
2583        }
2584        attr.parse_nested_meta(|meta| {
2585            if parse_shared_meta(&meta, &mut parsed.rename, &mut parsed.skip)? {
2586                return Ok(());
2587            }
2588            if meta.path.is_ident("get") {
2589                parsed.get = Some(meta.value()?.parse()?);
2590                return Ok(());
2591            }
2592            if meta.path.is_ident("set") {
2593                parsed.set = Some(meta.value()?.parse()?);
2594                return Ok(());
2595            }
2596            if meta.path.is_ident("typed") {
2597                parsed.typed = Some(meta.path.span());
2598                return Ok(());
2599            }
2600            Err(meta.error("unsupported `repe` method attribute"))
2601        })?;
2602    }
2603    attrs.retain(|attr| !attr.path().is_ident("repe"));
2604    validate_method_attrs(&parsed)?;
2605    Ok(parsed)
2606}
2607
2608/// Reject combinations of method attributes that contradict each other, before
2609/// any of them reaches code generation.
2610fn validate_method_attrs(attrs: &MethodAttrs) -> syn::Result<()> {
2611    if let (Some(get), Some(_)) = (&attrs.get, &attrs.set) {
2612        return Err(syn::Error::new_spanned(
2613            get,
2614            "a method is either the `get` half of a field-shaped endpoint or the `set` half, not \
2615             both: one takes no arguments and returns the value, the other takes the value and \
2616             returns nothing",
2617        ));
2618    }
2619    let Some(endpoint) = attrs.accessor_endpoint() else {
2620        if let Some(typed) = attrs.typed {
2621            return Err(syn::Error::new(
2622                typed,
2623                "`#[repe(typed)]` applies to the `get` half of a field-shaped endpoint; an \
2624                 ordinary method's return value is always encoded as JSON",
2625            ));
2626        }
2627        return Ok(());
2628    };
2629    if attrs.skip {
2630        return Err(syn::Error::new_spanned(
2631            endpoint,
2632            "`#[repe(skip)]` and `#[repe(get/set)]` contradict each other: one withholds the \
2633             method from the served surface, the other publishes it",
2634        ));
2635    }
2636    if attrs.rename.is_some() {
2637        return Err(syn::Error::new_spanned(
2638            endpoint,
2639            "`#[repe(rename = \"...\")]` has nothing to rename here: the endpoint of a \
2640             field-shaped accessor is the name given to `get`/`set`",
2641        ));
2642    }
2643    if attrs.typed.is_some() && attrs.set.is_some() {
2644        return Err(syn::Error::new_spanned(
2645            endpoint,
2646            "`#[repe(typed)]` describes how a value is *encoded* into a response, so it belongs \
2647             on the `get` half; a `set` decodes whatever the client sent",
2648        ));
2649    }
2650    let value = endpoint.value();
2651    if value.is_empty() {
2652        return Err(syn::Error::new_spanned(
2653            endpoint,
2654            "a field-shaped endpoint needs a name",
2655        ));
2656    }
2657    if value.contains('/') {
2658        return Err(syn::Error::new_spanned(
2659            endpoint,
2660            "a field-shaped endpoint is one path segment below the struct root, so it cannot \
2661             contain `/`",
2662        ));
2663    }
2664    Ok(())
2665}
2666
2667/// Turn one signature from a `#[repe::methods]` block into a published method,
2668/// or `Ok(None)` for an associated function that is not one.
2669fn parse_impl_method(
2670    sig: &Signature,
2671    remaining_attrs: &[Attribute],
2672    attrs: MethodAttrs,
2673) -> syn::Result<Option<(Published, MethodSpec)>> {
2674    let Some(FnArg::Receiver(receiver)) = sig.inputs.first() else {
2675        // An associated function has no instance to dispatch on. `Self::new()`
2676        // and friends belong in the block; they are simply not endpoints.
2677        if let Some(endpoint) = attrs.accessor_endpoint() {
2678            return Err(syn::Error::new_spanned(
2679                endpoint,
2680                "a field-shaped endpoint is served by a method on the instance, so its halves \
2681                 need a `&self` or `&mut self` receiver",
2682            ));
2683        }
2684        return Ok(None);
2685    };
2686
2687    // Conditional compilation is applied *after* attribute macros run, so a
2688    // published `#[cfg]` method would be dispatched to whether or not it exists
2689    // — and the resulting error points at the user's own definition saying it
2690    // is missing. Refuse instead of generating that.
2691    if let Some(cfg) = remaining_attrs
2692        .iter()
2693        .find(|attr| attr.path().is_ident("cfg") || attr.path().is_ident("cfg_attr"))
2694    {
2695        return Err(syn::Error::new_spanned(
2696            cfg,
2697            "`#[repe::methods]` cannot publish a conditionally-compiled method: `#[cfg]` is \
2698             applied after this macro runs, so the endpoint would be generated even when the \
2699             method is not. Move it to a plain `impl` block, or add `#[repe(skip)]` and expose \
2700             an unconditional wrapper.",
2701        ));
2702    }
2703
2704    if receiver.reference.is_none() {
2705        return Err(syn::Error::new_spanned(
2706            receiver,
2707            "`#[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)",
2708        ));
2709    }
2710    let kind = if receiver.mutability.is_some() {
2711        ReceiverKind::Mut
2712    } else {
2713        ReceiverKind::Ref
2714    };
2715
2716    if sig.asyncness.is_some() {
2717        return Err(syn::Error::new_spanned(
2718            sig.asyncness,
2719            "`#[repe::methods]` cannot publish an async method; the struct router dispatches synchronously (add `#[repe(skip)]` to exclude it)",
2720        ));
2721    }
2722    if sig.unsafety.is_some() {
2723        return Err(syn::Error::new_spanned(
2724            sig.unsafety,
2725            "`#[repe::methods]` cannot publish an unsafe method (add `#[repe(skip)]` to exclude it)",
2726        ));
2727    }
2728    if let Some(variadic) = &sig.variadic {
2729        return Err(syn::Error::new_spanned(
2730            variadic,
2731            "`#[repe::methods]` cannot publish a variadic method (add `#[repe(skip)]` to exclude it)",
2732        ));
2733    }
2734    if sig
2735        .generics
2736        .params
2737        .iter()
2738        .any(|param| !matches!(param, syn::GenericParam::Lifetime(_)))
2739    {
2740        return Err(syn::Error::new_spanned(
2741            &sig.generics,
2742            "`#[repe::methods]` cannot publish a generic method; the dispatch table needs one concrete signature (add `#[repe(skip)]` to exclude it)",
2743        ));
2744    }
2745
2746    // Names come from the signature where there is one to take. A pattern that
2747    // is not an identifier (`_`, a destructuring pattern) gets a positional
2748    // stand-in that cannot collide with a real parameter name, since the two
2749    // share one namespace in an object-form body.
2750    let mut args: Vec<(Ident, Type)> = Vec::new();
2751    for (index, input) in sig.inputs.iter().skip(1).enumerate() {
2752        let FnArg::Typed(pat_type) = input else {
2753            continue;
2754        };
2755        if matches!(&*pat_type.ty, Type::Reference(_)) {
2756            return Err(syn::Error::new_spanned(
2757                &pat_type.ty,
2758                "`#[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)",
2759            ));
2760        }
2761        if matches!(&*pat_type.ty, Type::ImplTrait(_)) {
2762            return Err(syn::Error::new_spanned(
2763                &pat_type.ty,
2764                "`#[repe::methods]` needs a nameable argument type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
2765            ));
2766        }
2767        let name = match &*pat_type.pat {
2768            syn::Pat::Ident(pat_ident) => pat_ident.ident.clone(),
2769            _ => format_ident!("_{}", index),
2770        };
2771        args.push((name, (*pat_type.ty).clone()));
2772    }
2773
2774    let ret_ty: Type = match &sig.output {
2775        ReturnType::Default => syn::parse_quote! { () },
2776        ReturnType::Type(_, ty) => (**ty).clone(),
2777    };
2778    if matches!(ret_ty, Type::ImplTrait(_)) {
2779        return Err(syn::Error::new_spanned(
2780            &sig.output,
2781            "`#[repe::methods]` needs a nameable return type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
2782        ));
2783    }
2784    let ret = classify_return(&ret_ty);
2785    let signature_display = build_signature_string(kind, &args, &ret);
2786
2787    let (published, endpoint) = match (&attrs.get, &attrs.set) {
2788        (Some(name), _) => {
2789            if !args.is_empty() {
2790                return Err(syn::Error::new_spanned(
2791                    &sig.inputs,
2792                    "the `get` half of a field-shaped endpoint takes no arguments: a client reads \
2793                     it the way it reads a field, with no request body to decode them from",
2794                ));
2795            }
2796            if ret.ok_is_unit() {
2797                return Err(syn::Error::new_spanned(
2798                    &sig.output,
2799                    "the `get` half of a field-shaped endpoint has to return the value; a read \
2800                     that yields nothing has nothing to publish",
2801                ));
2802            }
2803            (
2804                Published::Get {
2805                    typed: attrs.typed.is_some(),
2806                },
2807                name.value(),
2808            )
2809        }
2810        (None, Some(name)) => {
2811            if args.len() != 1 {
2812                return Err(syn::Error::new_spanned(
2813                    &sig.inputs,
2814                    "the `set` half of a field-shaped endpoint takes exactly one argument: the \
2815                     request body *is* the new value, as it is for a field write",
2816                ));
2817            }
2818            if !ret.ok_is_unit() {
2819                return Err(syn::Error::new_spanned(
2820                    &sig.output,
2821                    "the `set` half of a field-shaped endpoint returns nothing (or \
2822                     `Result<(), E>`): a field write is acknowledged with `null`, so a returned \
2823                     value would be silently dropped",
2824                ));
2825            }
2826            (Published::Set, name.value())
2827        }
2828        (None, None) => (
2829            Published::Method,
2830            attrs.rename.unwrap_or_else(|| sig.ident.to_string()),
2831        ),
2832    };
2833
2834    Ok(Some((
2835        published,
2836        MethodSpec {
2837            endpoint,
2838            method_ident: sig.ident.clone(),
2839            receiver: kind,
2840            args,
2841            ret,
2842            signature_display,
2843        },
2844    )))
2845}
2846
2847// ---------------------------------------------------------------------------
2848// `#[repe::plugin]` — the C-ABI plugin exports
2849// ---------------------------------------------------------------------------
2850
2851/// Export a [`Router`] constructor as a REPE C-ABI plugin.
2852///
2853/// (Every `repe` type below is linked by URL rather than by path: this is a
2854/// proc-macro crate, and it does not — cannot — depend on `repe`.)
2855///
2856/// Applied to a zero-argument function returning a `Router`, this emits the five
2857/// symbols a REPE host resolves after `dlopen` — `repe_plugin_interface_version`,
2858/// `repe_plugin_info`, `repe_plugin_init`, `repe_plugin_shutdown`, and
2859/// `repe_plugin_call` — each delegating to a `repe::plugin::PluginRuntime` built
2860/// from your function. See `repe::plugin` for the ABI contract and the
2861/// deployment requirements that come with it.
2862///
2863/// ```ignore
2864/// // Cargo.toml: [lib] crate-type = ["cdylib"]
2865/// use repe::server::Router;
2866///
2867/// #[repe::plugin(root = "/calculator")]
2868/// fn build() -> Router {
2869///     Router::new().with_typed("/calculator/add", |(a, b): (i64, i64)| Ok(a + b))
2870/// }
2871/// ```
2872///
2873/// # Arguments
2874///
2875/// * `root` (required) — the RPC path prefix this plugin claims, reported to the
2876///   host as `repe_plugin_data::root_path`. Must be an absolute JSON Pointer
2877///   prefix: leading `/`, no trailing `/`.
2878/// * `name` — defaults to the crate's `CARGO_PKG_NAME`.
2879/// * `version` — defaults to the crate's `CARGO_PKG_VERSION`.
2880///
2881/// Both defaults exist so the plugin's identity is not restated beside the
2882/// manifest that already carries it, and so it cannot drift from it.
2883///
2884/// The annotated function is left in place and stays callable, which is what
2885/// lets the same router be exercised by ordinary in-process tests.
2886///
2887/// [`Router`]: https://docs.rs/repe/latest/repe/server/struct.Router.html
2888#[proc_macro_attribute]
2889pub fn plugin(attr: TokenStream, item: TokenStream) -> TokenStream {
2890    let mut args = PluginArgs::default();
2891    let parser = syn::meta::parser(|meta| args.parse(meta));
2892    parse_macro_input!(attr with parser);
2893
2894    let item_fn = parse_macro_input!(item as syn::ItemFn);
2895    match expand_plugin(args, item_fn) {
2896        Ok(tokens) => tokens.into(),
2897        Err(err) => err.to_compile_error().into(),
2898    }
2899}
2900
2901#[derive(Default)]
2902struct PluginArgs {
2903    name: Option<LitStr>,
2904    version: Option<LitStr>,
2905    root: Option<LitStr>,
2906}
2907
2908impl PluginArgs {
2909    fn parse(&mut self, meta: ParseNestedMeta) -> syn::Result<()> {
2910        if meta.path.is_ident("name") {
2911            self.name = Some(meta.value()?.parse()?);
2912        } else if meta.path.is_ident("version") {
2913            self.version = Some(meta.value()?.parse()?);
2914        } else if meta.path.is_ident("root") {
2915            self.root = Some(meta.value()?.parse()?);
2916        } else {
2917            return Err(meta.error(
2918                "unknown `#[repe::plugin]` argument; expected `root`, `name`, or `version`",
2919            ));
2920        }
2921        Ok(())
2922    }
2923}
2924
2925/// Reject a string that cannot survive the trip through a C `const char*`.
2926///
2927/// An interior nul truncates the string silently at the host, which surfaces as
2928/// a plugin that loads under a name nobody typed — worth catching here, where
2929/// the literal is in view.
2930fn reject_interior_nul(field: &str, literal: &LitStr) -> syn::Result<()> {
2931    if literal.value().contains('\0') {
2932        return Err(syn::Error::new_spanned(
2933            literal,
2934            format!(
2935                "`{field}` cannot contain a nul byte: it is handed to the host as a C string and \
2936                 would be truncated there"
2937            ),
2938        ));
2939    }
2940    Ok(())
2941}
2942
2943fn expand_plugin(args: PluginArgs, item_fn: syn::ItemFn) -> syn::Result<TokenStream2> {
2944    let repe = repe_crate_path();
2945
2946    let Some(root) = args.root else {
2947        return Err(syn::Error::new(
2948            Span::call_site(),
2949            "`#[repe::plugin]` needs a `root` path prefix, e.g. \
2950             `#[repe::plugin(root = \"/calculator\")]`",
2951        ));
2952    };
2953    reject_interior_nul("root", &root)?;
2954    let root_value = root.value();
2955    if !root_value.starts_with('/') {
2956        return Err(syn::Error::new_spanned(
2957            &root,
2958            "`root` must be an absolute JSON Pointer prefix, so it has to start with `/`",
2959        ));
2960    }
2961    if root_value.len() > 1 && root_value.ends_with('/') {
2962        return Err(syn::Error::new_spanned(
2963            &root,
2964            "`root` must not end with `/`: hosts prefix-match this against request paths, and the \
2965             trailing separator is not part of the prefix",
2966        ));
2967    }
2968
2969    // Default identity to the manifest rather than restating it. `concat!`
2970    // expands `env!` eagerly, so both branches produce one `&'static str`
2971    // literal usable in a `static` initializer.
2972    let name = match &args.name {
2973        Some(name) => {
2974            reject_interior_nul("name", name)?;
2975            quote! { #name }
2976        }
2977        None => quote! { env!("CARGO_PKG_NAME") },
2978    };
2979    let version = match &args.version {
2980        Some(version) => {
2981            reject_interior_nul("version", version)?;
2982            quote! { #version }
2983        }
2984        None => quote! { env!("CARGO_PKG_VERSION") },
2985    };
2986
2987    if !item_fn.sig.inputs.is_empty() {
2988        return Err(syn::Error::new_spanned(
2989            &item_fn.sig.inputs,
2990            "`#[repe::plugin]` applies to a function taking no arguments: the host calls it \
2991             through a C ABI that has nothing to pass",
2992        ));
2993    }
2994    if !item_fn.sig.generics.params.is_empty() {
2995        return Err(syn::Error::new_spanned(
2996            &item_fn.sig.generics,
2997            "`#[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",
2998        ));
2999    }
3000    if item_fn.sig.asyncness.is_some() {
3001        return Err(syn::Error::new_spanned(
3002            &item_fn.sig,
3003            "`#[repe::plugin]` cannot be applied to an `async fn`: `repe_plugin_call` is \
3004             synchronous, with no runtime on the host side of the ABI to drive a future",
3005        ));
3006    }
3007
3008    let build = &item_fn.sig.ident;
3009
3010    Ok(quote! {
3011        #item_fn
3012
3013        #[doc(hidden)]
3014        static __REPE_PLUGIN_INFO: #repe::plugin::RepePluginData = #repe::plugin::RepePluginData {
3015            name: concat!(#name, "\0").as_ptr() as *const ::core::ffi::c_char,
3016            version: concat!(#version, "\0").as_ptr() as *const ::core::ffi::c_char,
3017            root_path: concat!(#root, "\0").as_ptr() as *const ::core::ffi::c_char,
3018        };
3019
3020        #[doc(hidden)]
3021        static __REPE_PLUGIN_RUNTIME: #repe::plugin::PluginRuntime =
3022            #repe::plugin::PluginRuntime::new(#build);
3023
3024        /// `repe_plugin_interface_version`: the ABI version this plugin was
3025        /// built against, which the host checks before reading anything else.
3026        #[unsafe(no_mangle)]
3027        pub extern "C" fn repe_plugin_interface_version() -> ::core::primitive::u32 {
3028            #repe::plugin::REPE_PLUGIN_INTERFACE_VERSION
3029        }
3030
3031        /// `repe_plugin_info`: this plugin's name, version, and claimed RPC path
3032        /// prefix. The pointee is a `static`, so it outlives every call.
3033        #[unsafe(no_mangle)]
3034        pub extern "C" fn repe_plugin_info() -> *const #repe::plugin::RepePluginData {
3035            &__REPE_PLUGIN_INFO
3036        }
3037
3038        /// `repe_plugin_init`: build the router. Optional for the host to call —
3039        /// the first request builds it lazily if this never runs.
3040        #[unsafe(no_mangle)]
3041        pub extern "C" fn repe_plugin_init() -> #repe::plugin::RepeResult {
3042            __REPE_PLUGIN_RUNTIME.init()
3043        }
3044
3045        /// `repe_plugin_shutdown`: refuse further requests.
3046        #[unsafe(no_mangle)]
3047        pub extern "C" fn repe_plugin_shutdown() {
3048            __REPE_PLUGIN_RUNTIME.shutdown()
3049        }
3050
3051        /// `repe_plugin_call`: dispatch one REPE request frame.
3052        ///
3053        /// # Safety
3054        ///
3055        /// `request` must point to `request_size` readable bytes, or be null
3056        /// with a `request_size` of 0. The returned buffer borrows from this
3057        /// thread's response buffer and is invalidated by this thread's next
3058        /// call, so the host must copy before calling again.
3059        #[unsafe(no_mangle)]
3060        pub unsafe extern "C" fn repe_plugin_call(
3061            request: *const ::core::ffi::c_char,
3062            request_size: ::core::primitive::u64,
3063        ) -> #repe::plugin::RepeBuffer {
3064            unsafe { __REPE_PLUGIN_RUNTIME.call(request, request_size) }
3065        }
3066    })
3067}
3068
3069#[cfg(test)]
3070mod tests {
3071    //! The rejections this macro makes at expansion time.
3072    //!
3073    //! Every one of these is a `syn::Error` the user reads as a compile error,
3074    //! and its text is the whole remedy. Asserting on the message here rather
3075    //! than on a captured rustc rendering keeps the check precise about the
3076    //! sentence we wrote and indifferent to how the compiler frames it, which
3077    //! changes between releases.
3078
3079    use super::*;
3080    use syn::parse_quote;
3081
3082    fn field_error(field: syn::Field) -> String {
3083        match parse_field(&field) {
3084            Err(err) => err.to_string(),
3085            Ok(spec) => panic!("`{}` was supposed to be rejected", spec.endpoint),
3086        }
3087    }
3088
3089    fn order(keys: &[&str]) -> ListingOrder {
3090        ListingOrder {
3091            keys: keys
3092                .iter()
3093                .map(|k| LitStr::new(k, Span::call_site()))
3094                .collect(),
3095            span: Span::call_site(),
3096        }
3097    }
3098
3099    fn declared(names: &[&str]) -> Vec<(&'static str, Span)> {
3100        // Leaked so the borrow outlives the call; a test binary's lifetime.
3101        names
3102            .iter()
3103            .map(|n| {
3104                (
3105                    &*Box::leak(n.to_string().into_boxed_str()),
3106                    Span::call_site(),
3107                )
3108            })
3109            .collect()
3110    }
3111
3112    // -----------------------------------------------------------------------
3113    // Field attribute conflicts
3114    // -----------------------------------------------------------------------
3115
3116    #[test]
3117    fn typed_and_nested_are_rejected_together() {
3118        let msg = field_error(parse_quote! {
3119            #[repe(typed, nested)]
3120            child: Child
3121        });
3122        assert!(
3123            msg.contains("BEVE typed array"),
3124            "the message should say why the two cannot combine, got: {msg}"
3125        );
3126    }
3127
3128    #[test]
3129    fn typed_and_nested_serde_are_rejected_together() {
3130        let msg = field_error(parse_quote! {
3131            #[repe(typed, nested_serde)]
3132            child: Child
3133        });
3134        assert!(msg.contains("BEVE typed array"), "got: {msg}");
3135    }
3136
3137    #[test]
3138    fn nested_and_nested_serde_are_rejected_together() {
3139        let msg = field_error(parse_quote! {
3140            #[repe(nested, nested_serde)]
3141            child: Child
3142        });
3143        assert!(
3144            msg.contains("two ways to descend into one field"),
3145            "the message should name the choice between them, got: {msg}"
3146        );
3147    }
3148
3149    #[test]
3150    fn readonly_on_a_struct_is_rejected_and_points_at_no_replace() {
3151        // The word is deliberately unclaimed at struct level: on a field it is
3152        // recursive, and the recursive meaning is the one a struct should get
3153        // if it ever gets one.
3154        let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(readonly)] }];
3155        let msg = match parse_struct_attrs(&attrs) {
3156            Err(err) => err.to_string(),
3157            Ok(_) => panic!("`readonly` on a struct is supposed to be rejected"),
3158        };
3159        assert!(
3160            msg.contains("no_replace") && msg.contains("recursive"),
3161            "the message should name the replacement and say why the two differ, got: {msg}"
3162        );
3163    }
3164
3165    #[test]
3166    fn no_replace_on_a_struct_is_accepted() {
3167        let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(no_replace)] }];
3168        let Ok(parsed) = parse_struct_attrs(&attrs) else {
3169            panic!("`no_replace` is supposed to be accepted");
3170        };
3171        assert!(parsed.no_replace);
3172    }
3173
3174    #[test]
3175    fn readonly_on_a_field_is_still_accepted() {
3176        // Unchanged, and the reason the struct-level spelling had to move.
3177        let field: syn::Field = parse_quote! { #[repe(readonly)] a: u64 };
3178        let Ok(spec) = parse_field(&field) else {
3179            panic!("`readonly` on a field is supposed to be accepted");
3180        };
3181        assert!(spec.attrs.readonly);
3182    }
3183
3184    #[test]
3185    fn an_unknown_field_attribute_is_rejected() {
3186        let msg = field_error(parse_quote! {
3187            #[repe(nonsense)]
3188            a: u64
3189        });
3190        assert!(
3191            msg.contains("unsupported `repe` field attribute"),
3192            "got: {msg}"
3193        );
3194    }
3195
3196    #[test]
3197    fn the_ordinary_combinations_are_accepted() {
3198        for field in [
3199            parse_quote! { #[repe(typed)] values: Vec<f64> },
3200            parse_quote! { #[repe(nested)] child: Child },
3201            parse_quote! { #[repe(nested_serde)] child: Child },
3202            parse_quote! { #[repe(nested, readonly)] child: Child },
3203            parse_quote! { #[repe(rename = "other")] a: u64 },
3204            parse_quote! { #[repe(skip)] a: u64 },
3205        ] {
3206            let field: syn::Field = field;
3207            assert!(parse_field(&field).is_ok());
3208        }
3209    }
3210
3211    // -----------------------------------------------------------------------
3212    // `#[repe(listing_order(..))]`, the half checked at macro time
3213    // -----------------------------------------------------------------------
3214
3215    #[test]
3216    fn an_order_naming_every_endpoint_is_accepted() {
3217        let d = declared(&["a", "b"]);
3218        assert!(validate_listing_order(&order(&["b", "a"]), &d, false).is_ok());
3219    }
3220
3221    #[test]
3222    fn a_key_named_twice_is_rejected() {
3223        let d = declared(&["a"]);
3224        let msg = validate_listing_order(&order(&["a", "a"]), &d, false)
3225            .expect_err("a repeated key is rejected")
3226            .to_string();
3227        assert!(msg.contains("named twice"), "got: {msg}");
3228    }
3229
3230    #[test]
3231    fn a_key_that_is_not_an_endpoint_is_rejected() {
3232        let d = declared(&["a"]);
3233        let msg = validate_listing_order(&order(&["a", "typo"]), &d, false)
3234            .expect_err("an unknown key is rejected")
3235            .to_string();
3236        assert!(
3237            msg.contains("`typo` is not an endpoint on this struct"),
3238            "the message should name the offending key, got: {msg}"
3239        );
3240    }
3241
3242    #[test]
3243    fn an_endpoint_missing_from_the_order_is_rejected() {
3244        let d = declared(&["a", "b"]);
3245        let msg = validate_listing_order(&order(&["a"]), &d, false)
3246            .expect_err("an omitted endpoint is rejected")
3247            .to_string();
3248        assert!(
3249            msg.contains("`b` is missing from"),
3250            "the message should name the omitted endpoint, got: {msg}"
3251        );
3252    }
3253
3254    #[test]
3255    fn an_impl_block_defers_the_unknown_key_check_to_the_const_assertion() {
3256        // The derive cannot see the impl block's endpoints, so an unrecognized
3257        // key here may still be one of them. `assert_listing_order` catches a
3258        // genuine typo at compile time instead; `repe-core`'s
3259        // `const_assertions.rs` pins that message.
3260        let d = declared(&["a"]);
3261        assert!(validate_listing_order(&order(&["a", "calc"]), &d, true).is_ok());
3262
3263        // The other direction is still checked, because a field the derive can
3264        // see is one it knows the order must name.
3265        let msg = validate_listing_order(&order(&["calc"]), &d, true)
3266            .expect_err("a field omitted from the order is still rejected")
3267            .to_string();
3268        assert!(msg.contains("`a` is missing from"), "got: {msg}");
3269    }
3270}