1use 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#[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#[derive(Clone, Copy, PartialEq, Eq)]
72enum Sink {
73 Value,
75 Encode,
77}
78
79impl Sink {
80 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 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 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 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 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 fn with_out(self, args: TokenStream2) -> TokenStream2 {
155 match self {
156 Sink::Value => args,
157 Sink::Encode => quote! { #args, out },
158 }
159 }
160}
161
162fn 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 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 let handshake = from_impl_block.then(|| {
224 let declared: Vec<LitStr> = endpoints
231 .iter()
232 .map(|(endpoint, _)| LitStr::new(endpoint, Span::call_site()))
233 .collect();
234 let order_check = struct_attrs.listing_order.as_ref().map(|order| {
238 let keys = &order.keys;
239 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 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 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 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 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 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 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
482fn 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
494fn 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 Err(_) => continue,
516 };
517 let ident = Ident::new(&name, Span::call_site());
518 return quote!(::#ident);
519 }
520 quote!(::repe)
523}
524
525fn 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#[derive(Default)]
547struct FieldAttrs {
548 rename: Option<String>,
549 skip: bool,
550 nested: bool,
551 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
571fn 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
658struct ReturnSpec {
660 ok_ty: Type,
662 fallible: bool,
665 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 receiver: ReceiverKind,
681 args: Vec<(Ident, Type)>,
682 ret: ReturnSpec,
683 signature_display: String,
684}
685
686struct StructAttrs {
687 methods: Vec<MethodSpec>,
688 methods_from_impl_block: bool,
691 no_replace: bool,
712 listing_order: Option<ListingOrder>,
732}
733
734struct 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 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 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
879fn 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
952enum ListingEntry<'a> {
965 Field(&'a FieldSpec),
967 Signature(&'a MethodSpec),
970 ImplNamed(LitStr),
974 ImplSignatures,
977 ImplAccessors,
979}
980
981fn 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 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
1025fn 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
1077fn 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
1091fn endpoint_path(endpoint: &str) -> LitStr {
1093 LitStr::new(&format!("/{endpoint}"), Span::call_site())
1094}
1095
1096#[derive(Clone, Copy)]
1111enum ListingSink {
1112 Value,
1113 Encode,
1114 Shared,
1115}
1116
1117impl ListingSink {
1118 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 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 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 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 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 fn wrap(self, entries: &[TokenStream2]) -> TokenStream2 {
1229 match self {
1230 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
1260fn 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 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 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 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 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
1368fn 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 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 let guard = field.attrs.readonly.then(|| {
1423 quote! {
1424 if body.is_some() {
1425 return #refuse;
1426 }
1427 }
1428 });
1429
1430 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 Sink::Encode => quote! { return #descend; },
1452 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 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 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#[derive(Clone, Copy)]
1574enum Raise {
1575 Result,
1577 Shared,
1580}
1581
1582impl Raise {
1583 fn err(self, err: TokenStream2) -> TokenStream2 {
1585 let refusal = self.refuse(err);
1586 quote! { return #refusal; }
1587 }
1588
1589 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 fn ok(self, expr: TokenStream2) -> TokenStream2 {
1599 match self {
1600 Raise::Result => expr,
1601 Raise::Shared => quote! { Some(#expr) },
1602 }
1603 }
1604}
1605
1606fn 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
1621fn 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
1630fn 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
1640fn 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
1676fn 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 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 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 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
1818fn 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 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
1868fn 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 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 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
1957fn 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 let write = if field.attrs.readonly {
2023 refuse.clone()
2024 } else {
2025 quote! { None }
2026 };
2027
2028 if field.attrs.nested {
2029 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 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
2087fn shared_body_terms(
2141 fields: &[FieldSpec],
2142 struct_attrs: &StructAttrs,
2143 from_impl_block: bool,
2144 repe: &TokenStream2,
2145) -> Vec<TokenStream2> {
2146 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
2205fn expand_methods(mut item_impl: ItemImpl) -> TokenStream2 {
2210 let repe = repe_crate_path();
2211 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 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
2241enum Published {
2244 Method,
2246 Get { typed: bool },
2249 Set,
2251}
2252
2253struct AccessorSpec {
2261 endpoint: String,
2262 get: MethodSpec,
2265 typed: bool,
2268 set: Option<MethodSpec>,
2272}
2273
2274#[derive(Default)]
2276struct PublishedItems {
2277 methods: Vec<MethodSpec>,
2278 accessors: Vec<AccessorSpec>,
2279}
2280
2281fn 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
2309fn 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 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 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 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
2396fn 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 let listing_needs_exclusive = published
2423 .accessors
2424 .iter()
2425 .any(|spec| !matches!(spec.get.receiver, ReceiverKind::Ref));
2426
2427 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 let _ = (&out, tail, &body);
2522 match *head {
2523 #(#shared_arms)*
2524 _ => #shared_invalid_path,
2525 }
2526 }
2527 });
2528
2529 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 get: Option<LitStr>,
2560 set: Option<LitStr>,
2562 typed: Option<Span>,
2566}
2567
2568impl MethodAttrs {
2569 fn accessor_endpoint(&self) -> Option<&LitStr> {
2571 self.get.as_ref().or(self.set.as_ref())
2572 }
2573}
2574
2575fn 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
2608fn 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
2667fn 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 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 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 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#[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
2925fn 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 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 #[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 #[unsafe(no_mangle)]
3034 pub extern "C" fn repe_plugin_info() -> *const #repe::plugin::RepePluginData {
3035 &__REPE_PLUGIN_INFO
3036 }
3037
3038 #[unsafe(no_mangle)]
3041 pub extern "C" fn repe_plugin_init() -> #repe::plugin::RepeResult {
3042 __REPE_PLUGIN_RUNTIME.init()
3043 }
3044
3045 #[unsafe(no_mangle)]
3047 pub extern "C" fn repe_plugin_shutdown() {
3048 __REPE_PLUGIN_RUNTIME.shutdown()
3049 }
3050
3051 #[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 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 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 #[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 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 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 #[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 let d = declared(&["a"]);
3261 assert!(validate_listing_order(&order(&["a", "calc"]), &d, true).is_ok());
3262
3263 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}