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 = #repe::__private::serde_json::to_value(&#expr)
107 .map_err(|source| #repe::StructError::Serialize {
108 path: String::from(#path),
109 source,
110 })?;
111 Ok(Some(value))
112 }
113 },
114 Sink::Encode => quote! { out.write(#path, &#expr) },
115 }
116 }
117
118 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 = #repe::__private::serde_json::from_value(value).map_err(|source| #repe::StructError::Deserialize {
338 path: String::from(""),
339 source,
340 })?;
341 return #root_write_ack;
342 }
343 }
344 };
345 let (signature, ret) = match sink {
346 Sink::Value => (
347 quote! {
348 fn repe_handle(
349 &mut self,
350 segments: &[&str],
351 body: Option<#repe::__private::serde_json::Value>,
352 )
353 },
354 quote! { #repe::structs::StructResult<Option<#repe::__private::serde_json::Value>> },
355 ),
356 Sink::Encode => (
357 quote! {
358 fn repe_handle_into(
359 &mut self,
360 segments: &[&str],
361 body: Option<#repe::__private::serde_json::Value>,
362 out: &mut #repe::structs::ResponseBody<'_>,
363 )
364 },
365 quote! { #repe::structs::StructResult<()> },
366 ),
367 };
368
369 bodies.push(quote! {
370 #signature -> #ret {
371 if segments.is_empty() {
372 #root_write
373 return #listing;
374 }
375
376 let (head, tail) = segments.split_first().unwrap();
377 match *head {
378 #(#field_arms)*
379 #(#method_arms)*
380 #fallthrough
381 }
382 }
383 });
384 }
385
386 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<#repe::__private::serde_json::Value>,
457 out: &mut #repe::structs::ResponseBody<'_>,
458 ) -> Option<#repe::structs::StructResult<()>> {
459 if segments.is_empty() {
460 #shared_root_write
461 return #shared_listing;
462 }
463
464 let (head, tail) = segments.split_first().unwrap();
465 match *head {
466 #(#shared_field_arms)*
467 #(#shared_method_arms)*
468 #shared_fallthrough
469 }
470 }
471 });
472
473 Ok(quote! {
474 impl #repe::RepeStruct for #struct_ident {
475 #(#bodies)*
476 }
477
478 #handshake
479 })
480}
481
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(
1179 self,
1180 repe: &TokenStream2,
1181 key: TokenStream2,
1182 produce: TokenStream2,
1183 ) -> TokenStream2 {
1184 match self {
1185 ListingSink::Value => quote! {
1186 map.insert(
1187 String::from(#key),
1188 (#produce)?.unwrap_or(#repe::__private::serde_json::Value::Null),
1189 );
1190 },
1191 ListingSink::Encode => quote! {
1192 __repe_obj.entry_with(#key, |__repe_nested| { #produce })?;
1193 },
1194 ListingSink::Shared => quote! {
1195 if let Err(__repe_err) = __repe_obj.entry_try_with(#key, |__repe_nested| {
1196 #produce
1197 })? {
1198 return Some(Err(__repe_err));
1199 }
1200 },
1201 }
1202 }
1203
1204 fn entry(
1206 self,
1207 repe: &TokenStream2,
1208 key: TokenStream2,
1209 value: TokenStream2,
1210 path: TokenStream2,
1211 ) -> TokenStream2 {
1212 match self {
1213 ListingSink::Value => quote! {
1214 {
1215 let __repe_value = #repe::__private::serde_json::to_value(&#value)
1216 .map_err(|source| #repe::StructError::Serialize {
1217 path: String::from(#path),
1218 source,
1219 })?;
1220 map.insert(String::from(#key), __repe_value);
1221 }
1222 },
1223 ListingSink::Encode => quote! { __repe_obj.entry(#key, &#value)?; },
1224 ListingSink::Shared => quote! {
1225 if let Err(__repe_err) = __repe_obj.entry(#key, &#value) {
1226 return Some(Err(__repe_err));
1227 }
1228 },
1229 }
1230 }
1231
1232 fn wrap(self, repe: &TokenStream2, entries: &[TokenStream2]) -> TokenStream2 {
1234 match self {
1235 ListingSink::Value => quote! {
1239 {
1240 let mut map = #repe::__private::serde_json::Map::new();
1241 #(#entries)*
1242 Ok(Some(#repe::__private::serde_json::Value::Object(map)))
1243 }
1244 },
1245 ListingSink::Encode => quote! {
1246 {
1247 let mut __repe_obj = out.object();
1248 #(#entries)*
1249 __repe_obj.finish();
1250 Ok(())
1251 }
1252 },
1253 ListingSink::Shared => quote! {
1254 {
1255 let mut __repe_obj = out.object();
1256 #(#entries)*
1257 __repe_obj.finish();
1258 Some(Ok(()))
1259 }
1260 },
1261 }
1262 }
1263}
1264
1265fn build_listing(
1280 entries: &[ListingEntry<'_>],
1281 repe: &TokenStream2,
1282 sink: ListingSink,
1283) -> TokenStream2 {
1284 let mut emitted = Vec::new();
1285
1286 for entry in entries {
1287 emitted.push(match entry {
1288 ListingEntry::Field(field) => {
1289 let key = LitStr::new(&field.endpoint, Span::call_site());
1290 let ident = &field.ident;
1291 if field.attrs.nested {
1292 let call = sink.child_call(repe, &field.ty, ident);
1295 sink.entry_with(
1296 repe,
1297 quote! { #key },
1298 sink.prepend(repe, call, quote! { #key }),
1299 )
1300 } else {
1301 let path = endpoint_path(&field.endpoint);
1308 sink.entry(repe, quote! { #key }, quote! { self.#ident }, quote! { #path })
1309 }
1310 }
1311 ListingEntry::Signature(method) => {
1312 let key = LitStr::new(&method.endpoint, Span::call_site());
1313 let signature = LitStr::new(&method.signature_display, Span::call_site());
1314 let path = endpoint_path(&method.endpoint);
1315 sink.entry(repe, quote! { #key }, quote! { #signature }, quote! { #path })
1316 }
1317 ListingEntry::ImplNamed(name) => {
1318 let resolved = impl_named_signature(name, repe);
1319 let accessor =
1320 sink.entry_with(repe, quote! { #name }, sink.accessor_call(repe, quote! { #name }));
1321 let path = endpoint_path(&name.value());
1322 let signature = sink.entry(
1323 repe,
1324 quote! { #name },
1325 quote! { __repe_signature },
1326 quote! { #path },
1327 );
1328 quote! {
1329 match #resolved {
1330 ::core::option::Option::Some(__repe_signature) => { #signature }
1331 ::core::option::Option::None => { #accessor }
1332 }
1333 }
1334 }
1335 ListingEntry::ImplSignatures => {
1336 let entry = sink.entry(repe, quote! { name }, quote! { signature }, quote! { name });
1339 quote! {
1340 for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
1341 #entry
1342 }
1343 }
1344 }
1345 ListingEntry::ImplAccessors => {
1360 let accessor =
1361 sink.entry_with(repe, quote! { name }, sink.accessor_call(repe, quote! { name }));
1362 quote! {
1363 for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
1364 #accessor
1365 }
1366 }
1367 }
1368 });
1369 }
1370
1371 sink.wrap(repe, &emitted)
1372}
1373
1374fn nested_dispatch(
1381 ty: &Type,
1382 ident: &Ident,
1383 key: LitStr,
1384 args: TokenStream2,
1385 repe: &TokenStream2,
1386 sink: Sink,
1387) -> TokenStream2 {
1388 let method = sink.struct_method();
1389 let args = sink.with_out(quote! { &mut self.#ident, #args });
1390 quote! {
1391 <#ty as #repe::RepeStruct>::#method(#args)
1392 .map_err(|err| #repe::structs::prepend_path(err, #key))
1393 }
1394}
1395
1396fn build_field_arms(fields: &[FieldSpec], repe: &TokenStream2, sink: Sink) -> Vec<TokenStream2> {
1397 let refuse = refuse_write(repe, Raise::Result);
1398 let subpath = refuse_subpath(repe, Raise::Result);
1399 let ack = sink.emit_null();
1400 let mut arms = Vec::new();
1401 for field in fields {
1402 if field.attrs.skip {
1403 continue;
1404 }
1405 let key = LitStr::new(&field.endpoint, Span::call_site());
1406 let ident = &field.ident;
1407 let path = endpoint_path(&field.endpoint);
1408
1409 if field.attrs.nested {
1410 let lift = |whole: TokenStream2| match sink {
1414 Sink::Value => quote! {
1415 {
1416 let nested = #whole?;
1417 Ok(Some(nested.unwrap_or(#repe::__private::serde_json::Value::Null)))
1418 }
1419 },
1420 Sink::Encode => whole,
1421 };
1422
1423 let guard = field.attrs.readonly.then(|| {
1429 quote! {
1430 if body.is_some() {
1431 return #refuse;
1432 }
1433 }
1434 });
1435
1436 let descend = nested_dispatch(
1446 &field.ty,
1447 ident,
1448 key.clone(),
1449 quote! { tail, body },
1450 repe,
1451 sink,
1452 );
1453 let body = match sink {
1454 Sink::Encode => quote! { return #descend; },
1458 Sink::Value => {
1461 let whole = lift(nested_dispatch(
1462 &field.ty,
1463 ident,
1464 key.clone(),
1465 quote! { &[], body },
1466 repe,
1467 sink,
1468 ));
1469 quote! {
1470 if tail.is_empty() {
1471 return #whole;
1472 }
1473 return #descend;
1474 }
1475 }
1476 };
1477 arms.push(quote! { #key => { #guard #body } });
1478 } else if field.attrs.nested_serde {
1479 let read = nested_serde_read(field, repe, sink, Raise::Result);
1486 let unresolved = refuse_unresolved(repe, Raise::Result);
1487 let write = if field.attrs.readonly {
1488 quote! { Some(_) => #refuse, }
1489 } else {
1490 quote! {
1491 Some(value) => {
1492 if tail.is_empty() {
1493 self.#ident = #repe::__private::serde_json::from_value(value)
1494 .map_err(|source| #repe::StructError::Deserialize {
1495 path: String::from(#path),
1496 source,
1497 })?;
1498 #ack
1499 } else {
1500 let mut __repe_value = #repe::__private::serde_json::to_value(&self.#ident)
1505 .map_err(|source| #repe::StructError::Serialize {
1506 path: String::from(#path),
1507 source,
1508 })?;
1509 if #repe::structs::serde_pointer_set(&mut __repe_value, tail, value)
1510 .is_none()
1511 {
1512 return #unresolved;
1513 }
1514 self.#ident = #repe::__private::serde_json::from_value(__repe_value)
1515 .map_err(|source| #repe::StructError::Deserialize {
1516 path: String::from(#path),
1517 source,
1518 })?;
1519 #ack
1520 }
1521 }
1522 }
1523 };
1524 arms.push(quote! {
1525 #key => {
1526 return match body {
1527 None => { #read }
1528 #write
1529 };
1530 }
1531 });
1532 } else {
1533 let read = if field.attrs.typed {
1534 sink.emit_typed_slice(repe, &path, quote! { self.#ident })
1535 } else {
1536 sink.emit_value(repe, &path, quote! { self.#ident })
1537 };
1538 let write = if field.attrs.readonly {
1539 quote! { Some(_) => #refuse, }
1540 } else {
1541 quote! {
1542 Some(value) => {
1543 self.#ident = #repe::__private::serde_json::from_value(value)
1544 .map_err(|source| #repe::StructError::Deserialize {
1545 path: String::from(#path),
1546 source,
1547 })?;
1548 #ack
1549 }
1550 }
1551 };
1552 arms.push(quote! {
1553 #key => {
1554 if !tail.is_empty() {
1555 return #subpath;
1556 }
1557 return match body {
1558 None => #read,
1559 #write
1560 };
1561 }
1562 });
1563 }
1564 }
1565 arms
1566}
1567
1568#[derive(Clone, Copy)]
1580enum Raise {
1581 Result,
1583 Shared,
1586}
1587
1588impl Raise {
1589 fn err(self, err: TokenStream2) -> TokenStream2 {
1591 let refusal = self.refuse(err);
1592 quote! { return #refusal; }
1593 }
1594
1595 fn refuse(self, err: TokenStream2) -> TokenStream2 {
1597 match self {
1598 Raise::Result => quote! { Err(#err) },
1599 Raise::Shared => quote! { Some(Err(#err)) },
1600 }
1601 }
1602
1603 fn ok(self, expr: TokenStream2) -> TokenStream2 {
1605 match self {
1606 Raise::Result => expr,
1607 Raise::Shared => quote! { Some(#expr) },
1608 }
1609 }
1610}
1611
1612fn refuse_write(repe: &TokenStream2, raise: Raise) -> TokenStream2 {
1620 raise.refuse(quote! {
1621 #repe::StructError::BodyUnexpected {
1622 path: #repe::structs::path_from_segments(segments),
1623 }
1624 })
1625}
1626
1627fn refuse_subpath(repe: &TokenStream2, raise: Raise) -> TokenStream2 {
1629 raise.refuse(quote! {
1630 #repe::StructError::InvalidSubpath {
1631 path: #repe::structs::path_from_segments(segments),
1632 }
1633 })
1634}
1635
1636fn refuse_unresolved(repe: &TokenStream2, raise: Raise) -> TokenStream2 {
1639 raise.refuse(quote! {
1640 #repe::StructError::InvalidPath {
1641 path: #repe::structs::path_from_segments(segments),
1642 }
1643 })
1644}
1645
1646fn nested_serde_read(
1651 field: &FieldSpec,
1652 repe: &TokenStream2,
1653 sink: Sink,
1654 raise: Raise,
1655) -> TokenStream2 {
1656 let ident = &field.ident;
1657 let path = endpoint_path(&field.endpoint);
1658 let whole = raise.ok(sink.emit_value(repe, &path, quote! { self.#ident }));
1659 let found = raise.ok(sink.emit_value(repe, &path, quote! { __repe_found }));
1660 let unresolved = refuse_unresolved(repe, raise);
1661 let unserializable = raise.refuse(quote! {
1662 #repe::StructError::Serialize {
1663 path: String::from(#path),
1664 source,
1665 }
1666 });
1667 quote! {
1668 if tail.is_empty() {
1669 #whole
1670 } else {
1671 match #repe::__private::serde_json::to_value(&self.#ident) {
1672 Ok(__repe_value) => match #repe::structs::serde_pointer(&__repe_value, tail) {
1673 Some(__repe_found) => #found,
1674 None => #unresolved,
1675 },
1676 Err(source) => #unserializable,
1677 }
1678 }
1679 }
1680}
1681
1682fn decode_method_args(
1689 method: &MethodSpec,
1690 bindings: &[Ident],
1691 repe: &TokenStream2,
1692 raise: Raise,
1693) -> TokenStream2 {
1694 if method.args.is_empty() {
1695 return quote! { let _ = &body; };
1696 }
1697 let path = endpoint_path(&method.endpoint);
1698 let missing = raise.err(quote! {
1699 #repe::StructError::BodyExpected {
1700 path: #repe::structs::path_from_segments(segments),
1701 }
1702 });
1703 let take_body = match raise {
1704 Raise::Result => quote! {
1705 let value = match body {
1706 Some(value) => value,
1707 None => { #missing }
1708 };
1709 },
1710 Raise::Shared => quote! {
1713 let value = match body.take() {
1714 Some(value) => value,
1715 None => { #missing }
1716 };
1717 },
1718 };
1719
1720 if method.args.len() == 1 {
1721 let binding = &bindings[0];
1722 let ty = &method.args[0].1;
1723 let undecodable = raise.err(quote! {
1724 #repe::StructError::Deserialize {
1725 path: String::from(#path),
1726 source,
1727 }
1728 });
1729 return quote! {
1730 #take_body
1731 let #binding: #ty = match #repe::__private::serde_json::from_value(value) {
1732 Ok(__repe_value) => __repe_value,
1733 Err(source) => { #undecodable }
1734 };
1735 };
1736 }
1737
1738 let names: Vec<LitStr> = method
1739 .args
1740 .iter()
1741 .map(|(ident, _)| LitStr::new(&ident.to_string(), Span::call_site()))
1742 .collect();
1743 let bad_args = raise.err(quote! { __repe_err });
1744 let decls = method.args.iter().zip(bindings).map(|((_, ty), binding)| {
1745 let bad_args = bad_args.clone();
1746 quote! {
1747 let #binding: #ty = match __repe_args.next_arg() {
1748 Ok(__repe_value) => __repe_value,
1749 Err(__repe_err) => { #bad_args }
1750 };
1751 }
1752 });
1753 quote! {
1754 #take_body
1755 let mut __repe_args = match #repe::structs::MethodArgs::new(#path, &[#(#names),*], value) {
1756 Ok(__repe_args) => __repe_args,
1757 Err(__repe_err) => { #bad_args }
1758 };
1759 #(#decls)*
1760 }
1761}
1762
1763fn build_method_arms(
1764 methods: &[MethodSpec],
1765 repe: &TokenStream2,
1766 sink: Sink,
1767 raise: Raise,
1768) -> Vec<TokenStream2> {
1769 methods
1770 .iter()
1771 .map(|method| build_method_arm(method, repe, sink, raise))
1772 .collect()
1773}
1774
1775fn build_method_arm(
1776 method: &MethodSpec,
1777 repe: &TokenStream2,
1778 sink: Sink,
1779 raise: Raise,
1780) -> TokenStream2 {
1781 let key = LitStr::new(&method.endpoint, Span::call_site());
1782 if matches!(raise, Raise::Shared) && !matches!(method.receiver, ReceiverKind::Ref) {
1786 return quote! { #key => None, };
1787 }
1788 let path = endpoint_path(&method.endpoint);
1789 let subpath = refuse_subpath(repe, raise);
1790 let method_ident = &method.method_ident;
1791
1792 let bindings: Vec<Ident> = (0..method.args.len())
1793 .map(|i| format_ident!("__repe_arg{}", i))
1794 .collect();
1795
1796 let decode_args = decode_method_args(method, &bindings, repe, raise);
1797
1798 let emit_ok = if method.ret.ok_is_unit() {
1799 sink.emit_null()
1800 } else {
1801 sink.emit_value(repe, &path, quote! { __repe_ok })
1802 };
1803 let invocation = quote_spanned! { method_ident.span()=>
1809 Self::#method_ident(self #(, #bindings)*)
1810 };
1811 let call = raise.ok(call_and_emit(invocation, &method.ret, emit_ok, repe, &path));
1812
1813 quote! {
1814 #key => {
1815 if !tail.is_empty() {
1816 return #subpath;
1817 }
1818 #decode_args
1819 #call
1820 }
1821 }
1822}
1823
1824fn call_and_emit(
1834 invocation: TokenStream2,
1835 ret: &ReturnSpec,
1836 emit_ok: TokenStream2,
1837 repe: &TokenStream2,
1838 path: &LitStr,
1839) -> TokenStream2 {
1840 if ret.fallible {
1841 let ok_pattern = if ret.ok_is_unit() {
1842 quote! { Ok(_) }
1843 } else {
1844 quote! { Ok(__repe_ok) }
1845 };
1846 quote! {
1847 match #invocation {
1848 #ok_pattern => #emit_ok,
1849 Err(__repe_err) => Err(#repe::StructError::Execution {
1850 path: String::from(#path),
1851 message: ::std::string::ToString::to_string(&__repe_err),
1852 }),
1853 }
1854 }
1855 } else if ret.ok_is_unit() {
1856 quote! {
1859 {
1860 #invocation;
1861 #emit_ok
1862 }
1863 }
1864 } else {
1865 quote! {
1866 {
1867 let __repe_ok = #invocation;
1868 #emit_ok
1869 }
1870 }
1871 }
1872}
1873
1874fn build_accessor_arm(
1886 accessor: &AccessorSpec,
1887 repe: &TokenStream2,
1888 sink: Sink,
1889 raise: Raise,
1890) -> TokenStream2 {
1891 let key = LitStr::new(&accessor.endpoint, Span::call_site());
1892 let path = endpoint_path(&accessor.endpoint);
1893 let subpath = refuse_subpath(repe, raise);
1894
1895 let read =
1899 if matches!(raise, Raise::Shared) && !matches!(accessor.get.receiver, ReceiverKind::Ref) {
1900 quote! { None }
1901 } else {
1902 let getter = &accessor.get.method_ident;
1903 let emit = if accessor.typed {
1904 sink.emit_typed_slice(repe, &path, quote! { __repe_ok })
1905 } else {
1906 sink.emit_value(repe, &path, quote! { __repe_ok })
1907 };
1908 raise.ok(call_and_emit(
1909 quote! { Self::#getter(self) },
1910 &accessor.get.ret,
1911 emit,
1912 repe,
1913 &path,
1914 ))
1915 };
1916
1917 let refuse = refuse_write(repe, raise);
1924 let write = match (&accessor.set, raise) {
1925 (None, _) => quote! { Some(_) => #refuse, },
1926 (Some(_), Raise::Shared) => quote! { Some(_) => None, },
1927 (Some(set), Raise::Result) => {
1928 let setter = &set.method_ident;
1929 let ty = &set.args[0].1;
1930 let call = call_and_emit(
1931 quote! { Self::#setter(self, __repe_arg) },
1932 &set.ret,
1933 sink.emit_null(),
1934 repe,
1935 &path,
1936 );
1937 quote! {
1938 Some(value) => {
1939 let __repe_arg: #ty = #repe::__private::serde_json::from_value(value)
1940 .map_err(|source| #repe::StructError::Deserialize {
1941 path: String::from(#path),
1942 source,
1943 })?;
1944 #call
1945 }
1946 }
1947 }
1948 };
1949
1950 quote! {
1951 #key => {
1952 if !tail.is_empty() {
1953 return #subpath;
1954 }
1955 match body {
1956 None => #read,
1957 #write
1958 }
1959 }
1960 }
1961}
1962
1963fn build_shared_field_arms(fields: &[FieldSpec], repe: &TokenStream2) -> Vec<TokenStream2> {
2016 let subpath = refuse_subpath(repe, Raise::Shared);
2017 let refuse = refuse_write(repe, Raise::Shared);
2018 let mut arms = Vec::new();
2019 for field in fields {
2020 if field.attrs.skip {
2021 continue;
2022 }
2023 let key = LitStr::new(&field.endpoint, Span::call_site());
2024 let ident = &field.ident;
2025 let path = endpoint_path(&field.endpoint);
2026 let write = if field.attrs.readonly {
2029 refuse.clone()
2030 } else {
2031 quote! { None }
2032 };
2033
2034 if field.attrs.nested {
2035 let ty = &field.ty;
2039 let forward = quote! {
2040 <#ty as #repe::RepeStruct>::repe_shared_into(&self.#ident, tail, body, out)
2041 .map(|__repe_result| {
2042 __repe_result.map_err(|err| #repe::structs::prepend_path(err, #key))
2043 })
2044 };
2045 if field.attrs.readonly {
2046 arms.push(quote! {
2047 #key => {
2048 if body.is_some() {
2049 return #refuse;
2050 }
2051 #forward
2052 }
2053 });
2054 } else {
2055 arms.push(quote! { #key => #forward, });
2056 }
2057 } else if field.attrs.nested_serde {
2058 let read = nested_serde_read(field, repe, Sink::Encode, Raise::Shared);
2063 arms.push(quote! {
2064 #key => {
2065 if body.is_some() {
2066 return #write;
2067 }
2068 #read
2069 }
2070 });
2071 } else {
2072 let read = if field.attrs.typed {
2073 Sink::Encode.emit_typed_slice(repe, &path, quote! { self.#ident })
2074 } else {
2075 Sink::Encode.emit_value(repe, &path, quote! { self.#ident })
2076 };
2077 arms.push(quote! {
2078 #key => {
2079 if !tail.is_empty() {
2080 return #subpath;
2081 }
2082 if body.is_some() {
2083 return #write;
2084 }
2085 Some(#read)
2086 }
2087 });
2088 }
2089 }
2090 arms
2091}
2092
2093fn shared_body_terms(
2147 fields: &[FieldSpec],
2148 struct_attrs: &StructAttrs,
2149 from_impl_block: bool,
2150 repe: &TokenStream2,
2151) -> Vec<TokenStream2> {
2152 if struct_attrs.no_replace
2155 || struct_attrs
2156 .methods
2157 .iter()
2158 .any(|m| matches!(m.receiver, ReceiverKind::Ref) && !m.args.is_empty())
2159 {
2160 return vec![quote! { true }];
2161 }
2162
2163 let mut terms = Vec::new();
2164 if from_impl_block {
2165 terms.push(quote! {
2166 <Self as #repe::structs::RepeMethods>::REPE_SHARED_SERVES_BODIES
2167 });
2168 }
2169 for field in fields {
2170 if field.attrs.skip {
2171 continue;
2172 }
2173 if field.attrs.readonly {
2174 return vec![quote! { true }];
2175 }
2176 if !field.attrs.nested {
2177 continue;
2178 }
2179 let ty = &field.ty;
2180 terms.push(quote! {
2181 <#ty as #repe::RepeStruct>::REPE_SHARED_SERVES_BODIES
2182 });
2183 }
2184 terms
2185}
2186
2187fn listing_decline_terms(
2188 fields: &[FieldSpec],
2189 from_impl_block: bool,
2190 repe: &TokenStream2,
2191) -> Vec<TokenStream2> {
2192 let mut terms = Vec::new();
2193 if from_impl_block {
2194 terms.push(quote! {
2195 <Self as #repe::structs::RepeMethods>::REPE_LISTING_NEEDS_EXCLUSIVE
2196 });
2197 }
2198 for field in fields {
2199 if field.attrs.skip || !field.attrs.nested {
2200 continue;
2201 }
2202 let ident = &field.ident;
2203 let ty = &field.ty;
2204 terms.push(quote! {
2205 <#ty as #repe::RepeStruct>::repe_listing_declines(&self.#ident)
2206 });
2207 }
2208 terms
2209}
2210
2211fn expand_methods(mut item_impl: ItemImpl) -> TokenStream2 {
2216 let repe = repe_crate_path();
2217 let mut stripped = Vec::new();
2221 for item in &mut item_impl.items {
2222 if let ImplItem::Fn(func) = item {
2223 stripped.push(take_method_attrs(&mut func.attrs));
2224 }
2225 }
2226
2227 match collect_methods(&item_impl, stripped) {
2228 Ok(published) => methods_impl(&item_impl, &published, &repe, false),
2229 Err(err) => {
2230 let error = err.to_compile_error();
2238 let empty = methods_impl(&item_impl, &PublishedItems::default(), &repe, true);
2239 quote! {
2240 #error
2241 #empty
2242 }
2243 }
2244 }
2245}
2246
2247enum Published {
2250 Method,
2252 Get { typed: bool },
2255 Set,
2257}
2258
2259struct AccessorSpec {
2267 endpoint: String,
2268 get: MethodSpec,
2271 typed: bool,
2274 set: Option<MethodSpec>,
2278}
2279
2280#[derive(Default)]
2282struct PublishedItems {
2283 methods: Vec<MethodSpec>,
2284 accessors: Vec<AccessorSpec>,
2285}
2286
2287fn reject_duplicate_accessor_half<'a>(
2294 halves: &(impl Iterator<Item = &'a MethodSpec> + Clone),
2295 key: &str,
2296) -> syn::Result<()> {
2297 let mut seen: Vec<&str> = Vec::new();
2298 for spec in halves.clone() {
2299 if seen.contains(&spec.endpoint.as_str()) {
2300 return Err(syn::Error::new(
2301 spec.method_ident.span(),
2302 format!(
2303 "two methods claim `#[repe({key} = \"{endpoint}\")]`; a field-shaped \
2304 endpoint has one read half and one write half, so one of these could never \
2305 be called. Give one of them a different endpoint.",
2306 endpoint = spec.endpoint
2307 ),
2308 ));
2309 }
2310 seen.push(&spec.endpoint);
2311 }
2312 Ok(())
2313}
2314
2315fn collect_methods(
2317 item_impl: &ItemImpl,
2318 stripped: Vec<syn::Result<MethodAttrs>>,
2319) -> syn::Result<PublishedItems> {
2320 if let Some((_, path, _)) = &item_impl.trait_ {
2321 return Err(syn::Error::new_spanned(
2322 path,
2323 "`#[repe::methods]` applies to an inherent impl block, not a trait impl",
2324 ));
2325 }
2326
2327 let mut methods: Vec<MethodSpec> = Vec::new();
2328 let mut getters: Vec<(MethodSpec, bool)> = Vec::new();
2331 let mut setters: Vec<MethodSpec> = Vec::new();
2332 let mut stripped = stripped.into_iter();
2333 for item in &item_impl.items {
2334 let ImplItem::Fn(func) = item else {
2335 continue;
2336 };
2337 let attrs = stripped
2338 .next()
2339 .expect("one parsed attribute set per impl fn")?;
2340 if attrs.skip {
2341 continue;
2342 }
2343 let Some((published, spec)) = parse_impl_method(&func.sig, &func.attrs, attrs)? else {
2344 continue;
2345 };
2346 match published {
2347 Published::Method => methods.push(spec),
2348 Published::Get { typed } => getters.push((spec, typed)),
2349 Published::Set => setters.push(spec),
2350 }
2351 }
2352
2353 reject_duplicate_accessor_half(&getters.iter().map(|(spec, _)| spec), "get")?;
2358 reject_duplicate_accessor_half(&setters.iter(), "set")?;
2359
2360 let mut accessors: Vec<AccessorSpec> = Vec::new();
2361 for (get, typed) in getters {
2362 let set = setters
2363 .iter()
2364 .position(|spec| spec.endpoint == get.endpoint)
2365 .map(|index| setters.remove(index));
2366 accessors.push(AccessorSpec {
2367 endpoint: get.endpoint.clone(),
2368 get,
2369 typed,
2370 set,
2371 });
2372 }
2373 if let Some(orphan) = setters.first() {
2377 return Err(syn::Error::new(
2378 orphan.method_ident.span(),
2379 format!(
2380 "`#[repe(set = \"{endpoint}\")]` has no matching \
2381 `#[repe(get = \"{endpoint}\")]` in this block: a field-shaped endpoint that \
2382 cannot be read has no value for the whole-struct listing to show. Add the read \
2383 half, or publish this as an ordinary method.",
2384 endpoint = orphan.endpoint
2385 ),
2386 ));
2387 }
2388
2389 let endpoints: Vec<(&str, Span)> = methods
2390 .iter()
2391 .map(|spec| (spec.endpoint.as_str(), spec.method_ident.span()))
2392 .chain(
2393 accessors
2394 .iter()
2395 .map(|spec| (spec.endpoint.as_str(), spec.get.method_ident.span())),
2396 )
2397 .collect();
2398 reject_duplicate_endpoints(&endpoints)?;
2399 Ok(PublishedItems { methods, accessors })
2400}
2401
2402fn methods_impl(
2404 item_impl: &ItemImpl,
2405 published: &PublishedItems,
2406 repe: &TokenStream2,
2407 recovered: bool,
2408) -> TokenStream2 {
2409 let self_ty = &item_impl.self_ty;
2410 let (impl_generics, _ty_generics, where_clause) = item_impl.generics.split_for_impl();
2411
2412 let signatures = published.methods.iter().map(|spec| {
2413 let endpoint = LitStr::new(&spec.endpoint, Span::call_site());
2414 let signature = LitStr::new(&spec.signature_display, Span::call_site());
2415 quote! { (#endpoint, #signature) }
2416 });
2417 let accessor_endpoints = published
2418 .accessors
2419 .iter()
2420 .map(|spec| LitStr::new(&spec.endpoint, Span::call_site()));
2421 let listing_needs_exclusive = published
2429 .accessors
2430 .iter()
2431 .any(|spec| !matches!(spec.get.receiver, ReceiverKind::Ref));
2432
2433 let shared_serves_bodies = published
2439 .methods
2440 .iter()
2441 .any(|spec| matches!(spec.receiver, ReceiverKind::Ref) && !spec.args.is_empty())
2442 || published.accessors.iter().any(|spec| match &spec.set {
2443 Some(set) => matches!(set.receiver, ReceiverKind::Ref),
2444 None => true,
2445 });
2446
2447 let mut bodies = Vec::new();
2448 for sink in [Sink::Value, Sink::Encode] {
2449 let arms = build_method_arms(&published.methods, repe, sink, Raise::Result)
2450 .into_iter()
2451 .chain(
2452 published
2453 .accessors
2454 .iter()
2455 .map(|accessor| build_accessor_arm(accessor, repe, sink, Raise::Result)),
2456 )
2457 .collect::<Vec<_>>();
2458 let (signature, ret, unused) = match sink {
2459 Sink::Value => (
2460 quote! {
2461 fn repe_call(
2462 &mut self,
2463 segments: &[&str],
2464 body: Option<#repe::__private::serde_json::Value>,
2465 )
2466 },
2467 quote! { #repe::structs::StructResult<Option<#repe::__private::serde_json::Value>> },
2468 quote! { let _ = &body; },
2469 ),
2470 Sink::Encode => (
2471 quote! {
2472 fn repe_call_into(
2473 &mut self,
2474 segments: &[&str],
2475 body: Option<#repe::__private::serde_json::Value>,
2476 out: &mut #repe::structs::ResponseBody<'_>,
2477 )
2478 },
2479 quote! { #repe::structs::StructResult<()> },
2480 quote! { let _ = &body; let _ = &out; },
2481 ),
2482 };
2483 bodies.push(quote! {
2484 #signature -> #ret {
2485 let Some((head, tail)) = segments.split_first() else {
2486 return Err(#repe::StructError::InvalidPath { path: String::from("") });
2487 };
2488 #unused
2489 match *head {
2490 #(#arms)*
2491 _ => Err(#repe::StructError::InvalidPath {
2492 path: #repe::structs::path_from_segments(segments),
2493 }),
2494 }
2495 }
2496 });
2497 }
2498
2499 let shared_arms = build_method_arms(&published.methods, repe, Sink::Encode, Raise::Shared)
2500 .into_iter()
2501 .chain(
2502 published
2503 .accessors
2504 .iter()
2505 .map(|accessor| build_accessor_arm(accessor, repe, Sink::Encode, Raise::Shared)),
2506 )
2507 .collect::<Vec<_>>();
2508 let shared_invalid_root = quote! {
2509 Some(Err(#repe::StructError::InvalidPath { path: String::from("") }))
2510 };
2511 let shared_invalid_path = quote! {
2512 Some(Err(#repe::StructError::InvalidPath {
2513 path: #repe::structs::path_from_segments(segments),
2514 }))
2515 };
2516 bodies.push(quote! {
2517 fn repe_call_shared_into(
2518 &self,
2519 segments: &[&str],
2520 body: &mut Option<#repe::__private::serde_json::Value>,
2521 out: &mut #repe::structs::ResponseBody<'_>,
2522 ) -> Option<#repe::structs::StructResult<()>> {
2523 let Some((head, tail)) = segments.split_first() else {
2524 return #shared_invalid_root;
2525 };
2526 let _ = (&out, tail, &body);
2528 match *head {
2529 #(#shared_arms)*
2530 _ => #shared_invalid_path,
2531 }
2532 }
2533 });
2534
2535 quote! {
2539 #item_impl
2540
2541 impl #impl_generics #repe::structs::RepeMethods for #self_ty #where_clause {
2542 const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)] =
2543 &[#(#signatures),*];
2544
2545 const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] =
2546 &[#(#accessor_endpoints),*];
2547
2548 const REPE_LISTING_NEEDS_EXCLUSIVE: bool = #listing_needs_exclusive;
2549
2550 const REPE_SHARED_SERVES_BODIES: bool = #shared_serves_bodies;
2551
2552 const REPE_TABLE_RECOVERED: bool = #recovered;
2553
2554 #(#bodies)*
2555 }
2556 }
2557}
2558
2559#[derive(Default)]
2560struct MethodAttrs {
2561 rename: Option<String>,
2562 skip: bool,
2563 get: Option<LitStr>,
2566 set: Option<LitStr>,
2568 typed: Option<Span>,
2572}
2573
2574impl MethodAttrs {
2575 fn accessor_endpoint(&self) -> Option<&LitStr> {
2577 self.get.as_ref().or(self.set.as_ref())
2578 }
2579}
2580
2581fn take_method_attrs(attrs: &mut Vec<Attribute>) -> syn::Result<MethodAttrs> {
2585 let mut parsed = MethodAttrs::default();
2586 for attr in attrs.iter() {
2587 if !attr.path().is_ident("repe") {
2588 continue;
2589 }
2590 attr.parse_nested_meta(|meta| {
2591 if parse_shared_meta(&meta, &mut parsed.rename, &mut parsed.skip)? {
2592 return Ok(());
2593 }
2594 if meta.path.is_ident("get") {
2595 parsed.get = Some(meta.value()?.parse()?);
2596 return Ok(());
2597 }
2598 if meta.path.is_ident("set") {
2599 parsed.set = Some(meta.value()?.parse()?);
2600 return Ok(());
2601 }
2602 if meta.path.is_ident("typed") {
2603 parsed.typed = Some(meta.path.span());
2604 return Ok(());
2605 }
2606 Err(meta.error("unsupported `repe` method attribute"))
2607 })?;
2608 }
2609 attrs.retain(|attr| !attr.path().is_ident("repe"));
2610 validate_method_attrs(&parsed)?;
2611 Ok(parsed)
2612}
2613
2614fn validate_method_attrs(attrs: &MethodAttrs) -> syn::Result<()> {
2617 if let (Some(get), Some(_)) = (&attrs.get, &attrs.set) {
2618 return Err(syn::Error::new_spanned(
2619 get,
2620 "a method is either the `get` half of a field-shaped endpoint or the `set` half, not \
2621 both: one takes no arguments and returns the value, the other takes the value and \
2622 returns nothing",
2623 ));
2624 }
2625 let Some(endpoint) = attrs.accessor_endpoint() else {
2626 if let Some(typed) = attrs.typed {
2627 return Err(syn::Error::new(
2628 typed,
2629 "`#[repe(typed)]` applies to the `get` half of a field-shaped endpoint; an \
2630 ordinary method's return value is always encoded as JSON",
2631 ));
2632 }
2633 return Ok(());
2634 };
2635 if attrs.skip {
2636 return Err(syn::Error::new_spanned(
2637 endpoint,
2638 "`#[repe(skip)]` and `#[repe(get/set)]` contradict each other: one withholds the \
2639 method from the served surface, the other publishes it",
2640 ));
2641 }
2642 if attrs.rename.is_some() {
2643 return Err(syn::Error::new_spanned(
2644 endpoint,
2645 "`#[repe(rename = \"...\")]` has nothing to rename here: the endpoint of a \
2646 field-shaped accessor is the name given to `get`/`set`",
2647 ));
2648 }
2649 if attrs.typed.is_some() && attrs.set.is_some() {
2650 return Err(syn::Error::new_spanned(
2651 endpoint,
2652 "`#[repe(typed)]` describes how a value is *encoded* into a response, so it belongs \
2653 on the `get` half; a `set` decodes whatever the client sent",
2654 ));
2655 }
2656 let value = endpoint.value();
2657 if value.is_empty() {
2658 return Err(syn::Error::new_spanned(
2659 endpoint,
2660 "a field-shaped endpoint needs a name",
2661 ));
2662 }
2663 if value.contains('/') {
2664 return Err(syn::Error::new_spanned(
2665 endpoint,
2666 "a field-shaped endpoint is one path segment below the struct root, so it cannot \
2667 contain `/`",
2668 ));
2669 }
2670 Ok(())
2671}
2672
2673fn parse_impl_method(
2676 sig: &Signature,
2677 remaining_attrs: &[Attribute],
2678 attrs: MethodAttrs,
2679) -> syn::Result<Option<(Published, MethodSpec)>> {
2680 let Some(FnArg::Receiver(receiver)) = sig.inputs.first() else {
2681 if let Some(endpoint) = attrs.accessor_endpoint() {
2684 return Err(syn::Error::new_spanned(
2685 endpoint,
2686 "a field-shaped endpoint is served by a method on the instance, so its halves \
2687 need a `&self` or `&mut self` receiver",
2688 ));
2689 }
2690 return Ok(None);
2691 };
2692
2693 if let Some(cfg) = remaining_attrs
2698 .iter()
2699 .find(|attr| attr.path().is_ident("cfg") || attr.path().is_ident("cfg_attr"))
2700 {
2701 return Err(syn::Error::new_spanned(
2702 cfg,
2703 "`#[repe::methods]` cannot publish a conditionally-compiled method: `#[cfg]` is \
2704 applied after this macro runs, so the endpoint would be generated even when the \
2705 method is not. Move it to a plain `impl` block, or add `#[repe(skip)]` and expose \
2706 an unconditional wrapper.",
2707 ));
2708 }
2709
2710 if receiver.reference.is_none() {
2711 return Err(syn::Error::new_spanned(
2712 receiver,
2713 "`#[repe::methods]` needs a `&self` or `&mut self` receiver; a method that consumes `self` cannot be called on a served object (add `#[repe(skip)]` to exclude it)",
2714 ));
2715 }
2716 let kind = if receiver.mutability.is_some() {
2717 ReceiverKind::Mut
2718 } else {
2719 ReceiverKind::Ref
2720 };
2721
2722 if sig.asyncness.is_some() {
2723 return Err(syn::Error::new_spanned(
2724 sig.asyncness,
2725 "`#[repe::methods]` cannot publish an async method; the struct router dispatches synchronously (add `#[repe(skip)]` to exclude it)",
2726 ));
2727 }
2728 if sig.unsafety.is_some() {
2729 return Err(syn::Error::new_spanned(
2730 sig.unsafety,
2731 "`#[repe::methods]` cannot publish an unsafe method (add `#[repe(skip)]` to exclude it)",
2732 ));
2733 }
2734 if let Some(variadic) = &sig.variadic {
2735 return Err(syn::Error::new_spanned(
2736 variadic,
2737 "`#[repe::methods]` cannot publish a variadic method (add `#[repe(skip)]` to exclude it)",
2738 ));
2739 }
2740 if sig
2741 .generics
2742 .params
2743 .iter()
2744 .any(|param| !matches!(param, syn::GenericParam::Lifetime(_)))
2745 {
2746 return Err(syn::Error::new_spanned(
2747 &sig.generics,
2748 "`#[repe::methods]` cannot publish a generic method; the dispatch table needs one concrete signature (add `#[repe(skip)]` to exclude it)",
2749 ));
2750 }
2751
2752 let mut args: Vec<(Ident, Type)> = Vec::new();
2757 for (index, input) in sig.inputs.iter().skip(1).enumerate() {
2758 let FnArg::Typed(pat_type) = input else {
2759 continue;
2760 };
2761 if matches!(&*pat_type.ty, Type::Reference(_)) {
2762 return Err(syn::Error::new_spanned(
2763 &pat_type.ty,
2764 "`#[repe::methods]` needs owned arguments, since each one is deserialized from the request body (use `String` rather than `&str`, or add `#[repe(skip)]` to exclude the method)",
2765 ));
2766 }
2767 if matches!(&*pat_type.ty, Type::ImplTrait(_)) {
2768 return Err(syn::Error::new_spanned(
2769 &pat_type.ty,
2770 "`#[repe::methods]` needs a nameable argument type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
2771 ));
2772 }
2773 let name = match &*pat_type.pat {
2774 syn::Pat::Ident(pat_ident) => pat_ident.ident.clone(),
2775 _ => format_ident!("_{}", index),
2776 };
2777 args.push((name, (*pat_type.ty).clone()));
2778 }
2779
2780 let ret_ty: Type = match &sig.output {
2781 ReturnType::Default => syn::parse_quote! { () },
2782 ReturnType::Type(_, ty) => (**ty).clone(),
2783 };
2784 if matches!(ret_ty, Type::ImplTrait(_)) {
2785 return Err(syn::Error::new_spanned(
2786 &sig.output,
2787 "`#[repe::methods]` needs a nameable return type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
2788 ));
2789 }
2790 let ret = classify_return(&ret_ty);
2791 let signature_display = build_signature_string(kind, &args, &ret);
2792
2793 let (published, endpoint) = match (&attrs.get, &attrs.set) {
2794 (Some(name), _) => {
2795 if !args.is_empty() {
2796 return Err(syn::Error::new_spanned(
2797 &sig.inputs,
2798 "the `get` half of a field-shaped endpoint takes no arguments: a client reads \
2799 it the way it reads a field, with no request body to decode them from",
2800 ));
2801 }
2802 if ret.ok_is_unit() {
2803 return Err(syn::Error::new_spanned(
2804 &sig.output,
2805 "the `get` half of a field-shaped endpoint has to return the value; a read \
2806 that yields nothing has nothing to publish",
2807 ));
2808 }
2809 (
2810 Published::Get {
2811 typed: attrs.typed.is_some(),
2812 },
2813 name.value(),
2814 )
2815 }
2816 (None, Some(name)) => {
2817 if args.len() != 1 {
2818 return Err(syn::Error::new_spanned(
2819 &sig.inputs,
2820 "the `set` half of a field-shaped endpoint takes exactly one argument: the \
2821 request body *is* the new value, as it is for a field write",
2822 ));
2823 }
2824 if !ret.ok_is_unit() {
2825 return Err(syn::Error::new_spanned(
2826 &sig.output,
2827 "the `set` half of a field-shaped endpoint returns nothing (or \
2828 `Result<(), E>`): a field write is acknowledged with `null`, so a returned \
2829 value would be silently dropped",
2830 ));
2831 }
2832 (Published::Set, name.value())
2833 }
2834 (None, None) => (
2835 Published::Method,
2836 attrs.rename.unwrap_or_else(|| sig.ident.to_string()),
2837 ),
2838 };
2839
2840 Ok(Some((
2841 published,
2842 MethodSpec {
2843 endpoint,
2844 method_ident: sig.ident.clone(),
2845 receiver: kind,
2846 args,
2847 ret,
2848 signature_display,
2849 },
2850 )))
2851}
2852
2853#[proc_macro_attribute]
2895pub fn plugin(attr: TokenStream, item: TokenStream) -> TokenStream {
2896 let mut args = PluginArgs::default();
2897 let parser = syn::meta::parser(|meta| args.parse(meta));
2898 parse_macro_input!(attr with parser);
2899
2900 let item_fn = parse_macro_input!(item as syn::ItemFn);
2901 match expand_plugin(args, item_fn) {
2902 Ok(tokens) => tokens.into(),
2903 Err(err) => err.to_compile_error().into(),
2904 }
2905}
2906
2907#[derive(Default)]
2908struct PluginArgs {
2909 name: Option<LitStr>,
2910 version: Option<LitStr>,
2911 root: Option<LitStr>,
2912}
2913
2914impl PluginArgs {
2915 fn parse(&mut self, meta: ParseNestedMeta) -> syn::Result<()> {
2916 if meta.path.is_ident("name") {
2917 self.name = Some(meta.value()?.parse()?);
2918 } else if meta.path.is_ident("version") {
2919 self.version = Some(meta.value()?.parse()?);
2920 } else if meta.path.is_ident("root") {
2921 self.root = Some(meta.value()?.parse()?);
2922 } else {
2923 return Err(meta.error(
2924 "unknown `#[repe::plugin]` argument; expected `root`, `name`, or `version`",
2925 ));
2926 }
2927 Ok(())
2928 }
2929}
2930
2931fn reject_interior_nul(field: &str, literal: &LitStr) -> syn::Result<()> {
2937 if literal.value().contains('\0') {
2938 return Err(syn::Error::new_spanned(
2939 literal,
2940 format!(
2941 "`{field}` cannot contain a nul byte: it is handed to the host as a C string and \
2942 would be truncated there"
2943 ),
2944 ));
2945 }
2946 Ok(())
2947}
2948
2949fn expand_plugin(args: PluginArgs, item_fn: syn::ItemFn) -> syn::Result<TokenStream2> {
2950 let repe = repe_crate_path();
2951
2952 let Some(root) = args.root else {
2953 return Err(syn::Error::new(
2954 Span::call_site(),
2955 "`#[repe::plugin]` needs a `root` path prefix, e.g. \
2956 `#[repe::plugin(root = \"/calculator\")]`",
2957 ));
2958 };
2959 reject_interior_nul("root", &root)?;
2960 let root_value = root.value();
2961 if !root_value.starts_with('/') {
2962 return Err(syn::Error::new_spanned(
2963 &root,
2964 "`root` must be an absolute JSON Pointer prefix, so it has to start with `/`",
2965 ));
2966 }
2967 if root_value.len() > 1 && root_value.ends_with('/') {
2968 return Err(syn::Error::new_spanned(
2969 &root,
2970 "`root` must not end with `/`: hosts prefix-match this against request paths, and the \
2971 trailing separator is not part of the prefix",
2972 ));
2973 }
2974
2975 let name = match &args.name {
2979 Some(name) => {
2980 reject_interior_nul("name", name)?;
2981 quote! { #name }
2982 }
2983 None => quote! { env!("CARGO_PKG_NAME") },
2984 };
2985 let version = match &args.version {
2986 Some(version) => {
2987 reject_interior_nul("version", version)?;
2988 quote! { #version }
2989 }
2990 None => quote! { env!("CARGO_PKG_VERSION") },
2991 };
2992
2993 if !item_fn.sig.inputs.is_empty() {
2994 return Err(syn::Error::new_spanned(
2995 &item_fn.sig.inputs,
2996 "`#[repe::plugin]` applies to a function taking no arguments: the host calls it \
2997 through a C ABI that has nothing to pass",
2998 ));
2999 }
3000 if !item_fn.sig.generics.params.is_empty() {
3001 return Err(syn::Error::new_spanned(
3002 &item_fn.sig.generics,
3003 "`#[repe::plugin]` applies to a non-generic function: the exports are one fixed set of symbols, so there is no parameter for the host to choose",
3004 ));
3005 }
3006 if item_fn.sig.asyncness.is_some() {
3007 return Err(syn::Error::new_spanned(
3008 &item_fn.sig,
3009 "`#[repe::plugin]` cannot be applied to an `async fn`: `repe_plugin_call` is \
3010 synchronous, with no runtime on the host side of the ABI to drive a future",
3011 ));
3012 }
3013
3014 let build = &item_fn.sig.ident;
3015
3016 Ok(quote! {
3017 #item_fn
3018
3019 #[doc(hidden)]
3020 static __REPE_PLUGIN_INFO: #repe::plugin::RepePluginData = #repe::plugin::RepePluginData {
3021 name: concat!(#name, "\0").as_ptr() as *const ::core::ffi::c_char,
3022 version: concat!(#version, "\0").as_ptr() as *const ::core::ffi::c_char,
3023 root_path: concat!(#root, "\0").as_ptr() as *const ::core::ffi::c_char,
3024 };
3025
3026 #[doc(hidden)]
3027 static __REPE_PLUGIN_RUNTIME: #repe::plugin::PluginRuntime =
3028 #repe::plugin::PluginRuntime::new(#build);
3029
3030 #[unsafe(no_mangle)]
3033 pub extern "C" fn repe_plugin_interface_version() -> ::core::primitive::u32 {
3034 #repe::plugin::REPE_PLUGIN_INTERFACE_VERSION
3035 }
3036
3037 #[unsafe(no_mangle)]
3040 pub extern "C" fn repe_plugin_info() -> *const #repe::plugin::RepePluginData {
3041 &__REPE_PLUGIN_INFO
3042 }
3043
3044 #[unsafe(no_mangle)]
3047 pub extern "C" fn repe_plugin_init() -> #repe::plugin::RepeResult {
3048 __REPE_PLUGIN_RUNTIME.init()
3049 }
3050
3051 #[unsafe(no_mangle)]
3053 pub extern "C" fn repe_plugin_shutdown() {
3054 __REPE_PLUGIN_RUNTIME.shutdown()
3055 }
3056
3057 #[unsafe(no_mangle)]
3066 pub unsafe extern "C" fn repe_plugin_call(
3067 request: *const ::core::ffi::c_char,
3068 request_size: ::core::primitive::u64,
3069 ) -> #repe::plugin::RepeBuffer {
3070 unsafe { __REPE_PLUGIN_RUNTIME.call(request, request_size) }
3071 }
3072 })
3073}
3074
3075#[cfg(test)]
3076mod tests {
3077 use super::*;
3086 use syn::parse_quote;
3087
3088 fn field_error(field: syn::Field) -> String {
3089 match parse_field(&field) {
3090 Err(err) => err.to_string(),
3091 Ok(spec) => panic!("`{}` was supposed to be rejected", spec.endpoint),
3092 }
3093 }
3094
3095 fn order(keys: &[&str]) -> ListingOrder {
3096 ListingOrder {
3097 keys: keys
3098 .iter()
3099 .map(|k| LitStr::new(k, Span::call_site()))
3100 .collect(),
3101 span: Span::call_site(),
3102 }
3103 }
3104
3105 fn declared(names: &[&str]) -> Vec<(&'static str, Span)> {
3106 names
3108 .iter()
3109 .map(|n| {
3110 (
3111 &*Box::leak(n.to_string().into_boxed_str()),
3112 Span::call_site(),
3113 )
3114 })
3115 .collect()
3116 }
3117
3118 #[test]
3123 fn typed_and_nested_are_rejected_together() {
3124 let msg = field_error(parse_quote! {
3125 #[repe(typed, nested)]
3126 child: Child
3127 });
3128 assert!(
3129 msg.contains("BEVE typed array"),
3130 "the message should say why the two cannot combine, got: {msg}"
3131 );
3132 }
3133
3134 #[test]
3135 fn typed_and_nested_serde_are_rejected_together() {
3136 let msg = field_error(parse_quote! {
3137 #[repe(typed, nested_serde)]
3138 child: Child
3139 });
3140 assert!(msg.contains("BEVE typed array"), "got: {msg}");
3141 }
3142
3143 #[test]
3144 fn nested_and_nested_serde_are_rejected_together() {
3145 let msg = field_error(parse_quote! {
3146 #[repe(nested, nested_serde)]
3147 child: Child
3148 });
3149 assert!(
3150 msg.contains("two ways to descend into one field"),
3151 "the message should name the choice between them, got: {msg}"
3152 );
3153 }
3154
3155 #[test]
3156 fn readonly_on_a_struct_is_rejected_and_points_at_no_replace() {
3157 let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(readonly)] }];
3161 let msg = match parse_struct_attrs(&attrs) {
3162 Err(err) => err.to_string(),
3163 Ok(_) => panic!("`readonly` on a struct is supposed to be rejected"),
3164 };
3165 assert!(
3166 msg.contains("no_replace") && msg.contains("recursive"),
3167 "the message should name the replacement and say why the two differ, got: {msg}"
3168 );
3169 }
3170
3171 #[test]
3172 fn no_replace_on_a_struct_is_accepted() {
3173 let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(no_replace)] }];
3174 let Ok(parsed) = parse_struct_attrs(&attrs) else {
3175 panic!("`no_replace` is supposed to be accepted");
3176 };
3177 assert!(parsed.no_replace);
3178 }
3179
3180 #[test]
3181 fn readonly_on_a_field_is_still_accepted() {
3182 let field: syn::Field = parse_quote! { #[repe(readonly)] a: u64 };
3184 let Ok(spec) = parse_field(&field) else {
3185 panic!("`readonly` on a field is supposed to be accepted");
3186 };
3187 assert!(spec.attrs.readonly);
3188 }
3189
3190 #[test]
3191 fn an_unknown_field_attribute_is_rejected() {
3192 let msg = field_error(parse_quote! {
3193 #[repe(nonsense)]
3194 a: u64
3195 });
3196 assert!(
3197 msg.contains("unsupported `repe` field attribute"),
3198 "got: {msg}"
3199 );
3200 }
3201
3202 #[test]
3203 fn the_ordinary_combinations_are_accepted() {
3204 for field in [
3205 parse_quote! { #[repe(typed)] values: Vec<f64> },
3206 parse_quote! { #[repe(nested)] child: Child },
3207 parse_quote! { #[repe(nested_serde)] child: Child },
3208 parse_quote! { #[repe(nested, readonly)] child: Child },
3209 parse_quote! { #[repe(rename = "other")] a: u64 },
3210 parse_quote! { #[repe(skip)] a: u64 },
3211 ] {
3212 let field: syn::Field = field;
3213 assert!(parse_field(&field).is_ok());
3214 }
3215 }
3216
3217 #[test]
3222 fn an_order_naming_every_endpoint_is_accepted() {
3223 let d = declared(&["a", "b"]);
3224 assert!(validate_listing_order(&order(&["b", "a"]), &d, false).is_ok());
3225 }
3226
3227 #[test]
3228 fn a_key_named_twice_is_rejected() {
3229 let d = declared(&["a"]);
3230 let msg = validate_listing_order(&order(&["a", "a"]), &d, false)
3231 .expect_err("a repeated key is rejected")
3232 .to_string();
3233 assert!(msg.contains("named twice"), "got: {msg}");
3234 }
3235
3236 #[test]
3237 fn a_key_that_is_not_an_endpoint_is_rejected() {
3238 let d = declared(&["a"]);
3239 let msg = validate_listing_order(&order(&["a", "typo"]), &d, false)
3240 .expect_err("an unknown key is rejected")
3241 .to_string();
3242 assert!(
3243 msg.contains("`typo` is not an endpoint on this struct"),
3244 "the message should name the offending key, got: {msg}"
3245 );
3246 }
3247
3248 #[test]
3249 fn an_endpoint_missing_from_the_order_is_rejected() {
3250 let d = declared(&["a", "b"]);
3251 let msg = validate_listing_order(&order(&["a"]), &d, false)
3252 .expect_err("an omitted endpoint is rejected")
3253 .to_string();
3254 assert!(
3255 msg.contains("`b` is missing from"),
3256 "the message should name the omitted endpoint, got: {msg}"
3257 );
3258 }
3259
3260 #[test]
3261 fn an_impl_block_defers_the_unknown_key_check_to_the_const_assertion() {
3262 let d = declared(&["a"]);
3267 assert!(validate_listing_order(&order(&["a", "calc"]), &d, true).is_ok());
3268
3269 let msg = validate_listing_order(&order(&["calc"]), &d, true)
3272 .expect_err("a field omitted from the order is still rejected")
3273 .to_string();
3274 assert!(msg.contains("`a` is missing from"), "got: {msg}");
3275 }
3276}