use proc_macro::TokenStream;
use proc_macro_crate::{FoundCrate, crate_name};
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{ToTokens, format_ident, quote, quote_spanned};
use syn::{
Attribute, DeriveInput, Field, FnArg, GenericArgument, Ident, ImplItem, ItemImpl, LitStr,
PathArguments, ReturnType, Signature, Token, Type,
meta::ParseNestedMeta,
parse::{Parse, ParseBuffer, ParseStream},
parse_macro_input,
punctuated::Punctuated,
spanned::Spanned,
};
#[proc_macro_derive(RepeStruct, attributes(repe))]
pub fn derive_repe_struct(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match expand_repe_struct(&input) {
Ok(tokens) => tokens.into(),
Err(err) => err.to_compile_error().into(),
}
}
#[proc_macro_attribute]
pub fn methods(attr: TokenStream, item: TokenStream) -> TokenStream {
if !attr.is_empty() {
let attr: TokenStream2 = attr.into();
return syn::Error::new_spanned(attr, "`#[repe::methods]` takes no arguments")
.to_compile_error()
.into();
}
let item_impl = parse_macro_input!(item as ItemImpl);
expand_methods(item_impl).into()
}
fn emit_null() -> TokenStream2 {
quote! {
{
out.write_null();
Ok(())
}
}
}
fn emit_value(expr: TokenStream2) -> TokenStream2 {
emit_value_spanned(Span::call_site(), expr)
}
fn emit_value_spanned(span: Span, expr: TokenStream2) -> TokenStream2 {
quote_spanned! {span=>
{
out.write(&#expr);
Ok(())
}
}
}
fn emit_typed_slice(expr: TokenStream2) -> TokenStream2 {
emit_typed_slice_spanned(Span::call_site(), expr)
}
fn emit_typed_slice_spanned(span: Span, expr: TokenStream2) -> TokenStream2 {
quote_spanned! {span=>
{
out.write_typed_slice(&#expr[..]);
Ok(())
}
}
}
fn expand_repe_struct(input: &DeriveInput) -> syn::Result<TokenStream2> {
let repe = repe_crate_path();
let struct_ident = &input.ident;
let syn::Data::Struct(data_struct) = &input.data else {
return Err(syn::Error::new_spanned(
input,
"RepeStruct can only be derived for structs",
));
};
let fields = match &data_struct.fields {
syn::Fields::Named(named) => &named.named,
_ => {
return Err(syn::Error::new_spanned(
&input.ident,
"RepeStruct requires named fields",
));
}
};
let struct_attrs = parse_struct_attrs(&input.attrs)?;
let field_specs = fields
.iter()
.map(parse_field)
.collect::<syn::Result<Vec<_>>>()?;
let mut endpoints: Vec<(&str, Span)> = Vec::new();
for field in &field_specs {
if !field.attrs.skip {
endpoints.push((&field.endpoint, field.ident.span()));
}
}
for method in &struct_attrs.methods {
endpoints.push((&method.endpoint, method.method_ident.span()));
}
reject_duplicate_endpoints(&endpoints)?;
let from_impl_block = struct_attrs.methods_from_impl_block;
if let Some(order) = &struct_attrs.listing_order {
validate_listing_order(order, &endpoints, from_impl_block)?;
}
let entries = listing_entries(
&field_specs,
&struct_attrs.methods,
from_impl_block,
struct_attrs.listing_order.as_ref(),
);
let handshake = from_impl_block.then(|| {
let declared: Vec<LitStr> = endpoints
.iter()
.map(|(endpoint, _)| LitStr::new(endpoint, Span::call_site()))
.collect();
let order_check = struct_attrs.listing_order.as_ref().map(|order| {
let keys = &order.keys;
let assert = respan(quote! { #repe::structs::assert_listing_order }, order.span);
quote_spanned! { order.span=>
const _: () = #assert(
&[#(#keys),*],
&[#(#declared),*],
<#struct_ident as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES,
<#struct_ident as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS,
<#struct_ident as #repe::structs::RepeMethods>::REPE_TABLE_RECOVERED,
);
}
});
quote! {
impl #repe::structs::MethodsDeclared for #struct_ident {}
const _: () = #repe::structs::assert_no_endpoint_collision(
&[#(#declared),*],
<#struct_ident as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES,
<#struct_ident as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS,
);
#order_check
}
});
let decline_terms = listing_decline_terms(&field_specs, from_impl_block, &repe);
let listing_declines = if decline_terms.is_empty() {
quote! { false }
} else {
quote! { #(#decline_terms)||* }
};
let body_terms = shared_body_terms(&field_specs, &struct_attrs, from_impl_block, &repe);
let shared_serves_bodies = if body_terms.is_empty() {
quote! { false }
} else {
quote! { #(#body_terms)||* }
};
let mut bodies = Vec::new();
{
let listing = build_listing(&entries, &repe, Borrow::Exclusive);
let field_arms = build_field_arms(&field_specs, &repe, Borrow::Exclusive);
let method_arms = build_method_arms(&struct_attrs.methods, &repe, Borrow::Exclusive);
let fallthrough = if from_impl_block {
quote! {
_ => <Self as #repe::structs::RepeMethods>::repe_call_into(
self, segments, body, out,
),
}
} else {
quote! {
_ => Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
}),
}
};
let root_write = if struct_attrs.no_replace {
quote! {
if body.is_some() {
return Err(#repe::StructError::BodyUnexpected {
path: String::from(""),
});
}
}
} else {
let root_write_ack = emit_null();
quote! {
if let Some(__repe_body) = body {
__repe_body.read_into("", self)?;
return #root_write_ack;
}
}
};
bodies.push(quote! {
fn repe_handle_into(
&mut self,
segments: &[&str],
body: Option<#repe::structs::RequestBody<'_>>,
out: &mut #repe::structs::ResponseBody<'_>,
) -> #repe::structs::StructResult<()> {
if segments.is_empty() {
#root_write
return #listing;
}
let (head, tail) = segments.split_first().unwrap();
match *head {
#(#field_arms)*
#(#method_arms)*
#fallthrough
}
}
});
}
let shared_listing = {
let listing = build_listing(&entries, &repe, Borrow::Shared);
let guard = (!decline_terms.is_empty()).then(|| {
quote! {
if <Self as #repe::RepeStruct>::repe_listing_declines(self) {
return None;
}
}
});
quote! {
{
#guard
#listing
}
}
};
let shared_field_arms = build_field_arms(&field_specs, &repe, Borrow::Shared);
let shared_method_arms = build_method_arms(&struct_attrs.methods, &repe, Borrow::Shared);
let shared_fallthrough = if from_impl_block {
quote! {
_ => <Self as #repe::structs::RepeMethods>::repe_call_shared_into(
self, segments, body, out,
),
}
} else {
quote! {
_ => Some(Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
})),
}
};
let shared_root_write = if struct_attrs.no_replace {
quote! {
if body.is_some() {
return Some(Err(#repe::StructError::BodyUnexpected {
path: String::from(""),
}));
}
}
} else {
quote! {
if body.is_some() {
return None;
}
}
};
bodies.push(quote! {
fn repe_listing_declines(&self) -> bool {
#listing_declines
}
});
bodies.push(quote! {
const REPE_SHARED_SERVES_BODIES: bool = #shared_serves_bodies;
});
bodies.push(quote! {
fn repe_shared_into(
&self,
segments: &[&str],
body: Option<#repe::structs::RequestBody<'_>>,
out: &mut #repe::structs::ResponseBody<'_>,
) -> Option<#repe::structs::StructResult<()>> {
if segments.is_empty() {
#shared_root_write
return #shared_listing;
}
let (head, tail) = segments.split_first().unwrap();
match *head {
#(#shared_field_arms)*
#(#shared_method_arms)*
#shared_fallthrough
}
}
});
Ok(quote! {
impl #repe::RepeStruct for #struct_ident {
#(#bodies)*
}
#handshake
})
}
fn respan(tokens: TokenStream2, span: Span) -> TokenStream2 {
tokens
.into_iter()
.map(|mut tree| {
tree.set_span(span);
tree
})
.collect()
}
fn repe_crate_path() -> TokenStream2 {
for (package, itself) in [("repe", "repe"), ("repe-core", "repe_core")] {
let name = match crate_name(package) {
Ok(FoundCrate::Itself) => String::from(itself),
Ok(FoundCrate::Name(name)) => name,
Err(_) => continue,
};
let ident = Ident::new(&name, Span::call_site());
return quote!(::#ident);
}
quote!(::repe)
}
fn reject_duplicate_endpoints(endpoints: &[(&str, Span)]) -> syn::Result<()> {
for (index, (name, _)) in endpoints.iter().enumerate() {
if endpoints[..index].iter().any(|(prior, _)| prior == name) {
return Err(syn::Error::new(
endpoints[index].1,
format!(
"endpoint `{name}` is declared twice on this struct; one of them would be \
unreachable and the whole-struct listing would emit the key twice. Rename \
one with `#[repe(rename = \"...\")]`."
),
));
}
}
Ok(())
}
#[derive(Default)]
struct FieldAttrs {
rename: Option<String>,
skip: bool,
nested: bool,
readonly: bool,
typed: bool,
}
struct FieldSpec {
ident: Ident,
ty: Type,
attrs: FieldAttrs,
endpoint: String,
}
fn parse_shared_meta(
meta: &ParseNestedMeta<'_>,
rename: &mut Option<String>,
skip: &mut bool,
) -> syn::Result<bool> {
if meta.path.is_ident("skip") {
*skip = true;
return Ok(true);
}
if meta.path.is_ident("rename") {
let lit: LitStr = meta.value()?.parse()?;
*rename = Some(lit.value());
return Ok(true);
}
Ok(false)
}
fn parse_field(field: &Field) -> syn::Result<FieldSpec> {
let ident = field
.ident
.clone()
.ok_or_else(|| syn::Error::new(field.span(), "expected named field"))?;
let mut attrs = FieldAttrs::default();
for attr in &field.attrs {
if !attr.path().is_ident("repe") {
continue;
}
attr.parse_nested_meta(|meta| {
if parse_shared_meta(&meta, &mut attrs.rename, &mut attrs.skip)? {
return Ok(());
}
if meta.path.is_ident("nested") {
attrs.nested = true;
return Ok(());
}
if meta.path.is_ident("nested_serde") {
return Err(meta.error(
"`#[repe(nested_serde)]` is gone: it descended into a field by walking a \
`serde_json::Value` of it, and there is no tree to walk. Use \
`#[repe(nested)]` where the child can implement `RepeStruct`, and a \
structio adapter (`json::ReadAs` / `WriteAs`, named at the field as \
`field as Adapter`) for a type whose crate cannot depend on this one.",
));
}
if meta.path.is_ident("readonly") {
attrs.readonly = true;
return Ok(());
}
if meta.path.is_ident("typed") {
attrs.typed = true;
return Ok(());
}
Err(meta.error("unsupported `repe` field attribute"))
})?;
}
if attrs.typed && attrs.nested {
return Err(syn::Error::new(
field.span(),
"`#[repe(typed)]` encodes a numeric slice as a BEVE typed array, which a nested struct is not",
));
}
let endpoint = attrs.rename.clone().unwrap_or_else(|| ident.to_string());
Ok(FieldSpec {
ident,
ty: field.ty.clone(),
attrs,
endpoint,
})
}
#[derive(Debug, Clone, Copy)]
enum ReceiverKind {
Ref,
Mut,
}
struct ReturnSpec {
ok_ty: Type,
fallible: bool,
display: String,
}
impl ReturnSpec {
fn ok_is_unit(&self) -> bool {
matches!(&self.ok_ty, Type::Tuple(tuple) if tuple.elems.is_empty())
}
}
struct MethodSpec {
endpoint: String,
method_ident: Ident,
receiver: ReceiverKind,
args: Vec<(Ident, Type)>,
ret: ReturnSpec,
signature_display: String,
}
struct StructAttrs {
methods: Vec<MethodSpec>,
methods_from_impl_block: bool,
no_replace: bool,
listing_order: Option<ListingOrder>,
}
struct ListingOrder {
keys: Vec<LitStr>,
span: Span,
}
fn parse_struct_attrs(attrs: &[Attribute]) -> syn::Result<StructAttrs> {
let mut methods = Vec::new();
let mut methods_from_impl_block = false;
let mut no_replace = false;
let mut listing_order: Option<ListingOrder> = None;
for attr in attrs {
if !attr.path().is_ident("repe") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("no_replace") {
no_replace = true;
return Ok(());
}
if meta.path.is_ident("readonly") {
return Err(meta.error(
"`#[repe(readonly)]` is a field attribute, and on a field it is recursive: \
it refuses every write through the field. A struct wanting that marks its \
fields. To refuse a write of the *whole* object while its fields stay \
writable — which also drops the requirement that `Self` be readable at \
all, for a type no body describes — use `#[repe(no_replace)]`.",
));
}
if meta.path.is_ident("listing_order") {
let span = meta.path.span();
if listing_order.is_some() {
return Err(meta.error(
"`#[repe(listing_order(..))]` is given once and names every key; two \
lists cannot both be the order",
));
}
let content;
syn::parenthesized!(content in meta.input);
let keys: Punctuated<LitStr, Token![,]> =
content.parse_terminated(<LitStr as Parse>::parse, Token![,])?;
listing_order = Some(ListingOrder {
keys: keys.into_iter().collect(),
span,
});
return Ok(());
}
if meta.path.is_ident("methods") {
if !meta.input.peek(syn::token::Paren) {
methods_from_impl_block = true;
return Ok(());
}
let content;
syn::parenthesized!(content in meta.input);
let list: Punctuated<MethodSpec, Token![,]> =
content.parse_terminated(MethodSpec::parse, Token![,])?;
methods.extend(list);
Ok(())
} else {
Err(meta.error("unsupported `repe` attribute"))
}
})?;
}
Ok(StructAttrs {
methods,
methods_from_impl_block,
no_replace,
listing_order,
})
}
impl Parse for MethodSpec {
fn parse(input: ParseStream) -> syn::Result<Self> {
let lookahead: Ident = input.parse()?;
let (endpoint, method_ident) = if input.peek(Token![=]) {
input.parse::<Token![=]>()?;
let method: Ident = input.parse()?;
(lookahead.to_string(), method)
} else {
let method = lookahead.clone();
(lookahead.to_string(), method)
};
let content;
syn::parenthesized!(content in input);
let receiver = parse_receiver(&content)?;
let mut args = Vec::new();
while content.peek(Token![,]) {
content.parse::<Token![,]>()?;
if content.is_empty() {
break;
}
let arg_ident: Ident = content.parse()?;
content.parse::<Token![:]>()?;
let arg_ty: Type = content.parse()?;
args.push((arg_ident, arg_ty));
}
if !content.is_empty() {
return Err(content.error("unexpected tokens in method parameter list"));
}
let ret_ty: Type = if input.peek(Token![->]) {
input.parse::<Token![->]>()?;
input.parse::<Type>()?
} else {
syn::parse_quote! { () }
};
let ret = classify_return(&ret_ty);
let signature_display = build_signature_string(receiver, &args, &ret);
Ok(MethodSpec {
endpoint,
method_ident,
receiver,
args,
ret,
signature_display,
})
}
}
fn parse_receiver(input: &ParseBuffer<'_>) -> syn::Result<ReceiverKind> {
input.parse::<Token![&]>()?;
if input.peek(Token![mut]) {
input.parse::<Token![mut]>()?;
input.parse::<Token![self]>()?;
Ok(ReceiverKind::Mut)
} else {
input.parse::<Token![self]>()?;
Ok(ReceiverKind::Ref)
}
}
fn classify_return(ty: &Type) -> ReturnSpec {
let display = normalize_type_string(ty);
if let Type::Path(type_path) = ty
&& type_path.qself.is_none()
&& let Some(segment) = type_path.path.segments.last()
&& segment.ident == "Result"
&& let PathArguments::AngleBracketed(generics) = &segment.arguments
{
let type_args: Vec<&Type> = generics
.args
.iter()
.filter_map(|arg| match arg {
GenericArgument::Type(ty) => Some(ty),
_ => None,
})
.collect();
if matches!(type_args.len(), 1 | 2) {
return ReturnSpec {
ok_ty: type_args[0].clone(),
fallible: true,
display,
};
}
}
ReturnSpec {
ok_ty: ty.clone(),
fallible: false,
display,
}
}
fn build_signature_string(
receiver: ReceiverKind,
args: &[(Ident, Type)],
ret: &ReturnSpec,
) -> String {
let recv = match receiver {
ReceiverKind::Ref => "&self",
ReceiverKind::Mut => "&mut self",
};
let mut params = String::from(recv);
for (name, ty) in args {
params.push_str(", ");
params.push_str(&name.to_string());
params.push_str(": ");
params.push_str(&normalize_type_string(ty));
}
format!("fn({}) -> {}", params, ret.display)
}
fn normalize_type_string(ty: &Type) -> String {
ty.to_token_stream()
.to_string()
.replace(" ,", ",")
.replace(" :: ", "::")
.replace(" < ", "<")
.replace(" >", ">")
.replace("& '", "&'")
}
enum ListingEntry<'a> {
Field(&'a FieldSpec),
Signature(&'a MethodSpec),
ImplNamed(LitStr),
ImplSignatures,
ImplAccessors,
}
fn listing_entries<'a>(
fields: &'a [FieldSpec],
methods: &'a [MethodSpec],
from_impl_block: bool,
order: Option<&ListingOrder>,
) -> Vec<ListingEntry<'a>> {
let Some(order) = order else {
let mut entries: Vec<ListingEntry<'a>> = fields
.iter()
.filter(|field| !field.attrs.skip)
.map(ListingEntry::Field)
.collect();
entries.extend(methods.iter().map(ListingEntry::Signature));
if from_impl_block {
entries.push(ListingEntry::ImplSignatures);
entries.push(ListingEntry::ImplAccessors);
}
return entries;
};
order
.keys
.iter()
.map(|key| {
let name = key.value();
if let Some(field) = fields
.iter()
.find(|field| !field.attrs.skip && field.endpoint == name)
{
ListingEntry::Field(field)
} else if let Some(method) = methods.iter().find(|method| method.endpoint == name) {
ListingEntry::Signature(method)
} else {
ListingEntry::ImplNamed(key.clone())
}
})
.collect()
}
fn validate_listing_order(
order: &ListingOrder,
declared: &[(&str, Span)],
from_impl_block: bool,
) -> syn::Result<()> {
let mut seen: Vec<String> = Vec::new();
for key in &order.keys {
let name = key.value();
if seen.contains(&name) {
return Err(syn::Error::new_spanned(
key,
format!(
"`{name}` is named twice in `#[repe(listing_order(..))]`; the listing emits \
each key once, so the second position could never be used"
),
));
}
if !from_impl_block && !declared.iter().any(|(endpoint, _)| *endpoint == name) {
return Err(syn::Error::new_spanned(
key,
format!(
"`{name}` is not an endpoint on this struct, so the listing has nothing to \
emit for it"
),
));
}
seen.push(name);
}
for (endpoint, span) in declared {
if !seen.iter().any(|name| name == endpoint) {
return Err(syn::Error::new(
*span,
format!(
"`{endpoint}` is missing from `#[repe(listing_order(..))]`, which names the \
whole-object listing's keys in full. An omitted endpoint would disappear \
from every whole-object read while still answering on its own path."
),
));
}
}
Ok(())
}
fn impl_named_signature(name: &LitStr, repe: &TokenStream2) -> TokenStream2 {
quote! {
const {
#repe::structs::listed_signature(
<Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES,
#name,
)
}
}
}
fn endpoint_path(endpoint: &str) -> LitStr {
LitStr::new(&format!("/{endpoint}"), Span::call_site())
}
fn listing_entry(key: TokenStream2, value: TokenStream2) -> TokenStream2 {
quote! { __repe_obj.entry(#key, &#value); }
}
fn build_listing(
entries: &[ListingEntry<'_>],
repe: &TokenStream2,
borrow: Borrow,
) -> TokenStream2 {
let mut emitted = Vec::new();
let mut fixed = 0usize;
let mut variable: Vec<TokenStream2> = Vec::new();
for entry in entries {
match entry {
ListingEntry::ImplSignatures => variable.push(quote! {
<Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES.len()
}),
ListingEntry::ImplAccessors => variable.push(quote! {
<Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS.len()
}),
_ => fixed += 1,
}
emitted.push(match entry {
ListingEntry::Field(field) => {
let key = LitStr::new(&field.endpoint, Span::call_site());
let ident = &field.ident;
if field.attrs.nested {
let call = borrow.child_call(
repe,
&field.ty,
ident,
quote! { &[], None },
quote! { __repe_nested },
);
borrow.entry_with(
quote! { #key },
borrow.prepend(repe, call, quote! { #key }),
)
} else {
listing_entry(quote! { #key }, quote! { self.#ident })
}
}
ListingEntry::Signature(method) => {
let key = LitStr::new(&method.endpoint, Span::call_site());
let signature = LitStr::new(&method.signature_display, Span::call_site());
listing_entry(quote! { #key }, quote! { #signature })
}
ListingEntry::ImplNamed(name) => {
let resolved = impl_named_signature(name, repe);
let accessor =
borrow.entry_with(quote! { #name }, borrow.accessor_call(repe, quote! { #name }));
let signature = listing_entry(quote! { #name }, quote! { __repe_signature });
quote! {
match #resolved {
::core::option::Option::Some(__repe_signature) => { #signature }
::core::option::Option::None => { #accessor }
}
}
}
ListingEntry::ImplSignatures => {
let entry = listing_entry(quote! { name }, quote! { signature });
quote! {
for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
#entry
}
}
}
ListingEntry::ImplAccessors => {
let accessor =
borrow.entry_with(quote! { name }, borrow.accessor_call(repe, quote! { name }));
quote! {
for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
#accessor
}
}
}
});
}
let count = quote! { #fixed #( + #variable)* };
borrow.wrap(&emitted, count)
}
fn build_field_arms(
fields: &[FieldSpec],
repe: &TokenStream2,
borrow: Borrow,
) -> Vec<TokenStream2> {
let refuse = refuse_write(repe, borrow);
let subpath = refuse_subpath(repe, borrow);
let ack = borrow.ok(emit_null());
let mut arms = Vec::new();
for field in fields {
if field.attrs.skip {
continue;
}
let key = LitStr::new(&field.endpoint, Span::call_site());
let ident = &field.ident;
let path = endpoint_path(&field.endpoint);
if field.attrs.nested {
let guard = field.attrs.readonly.then(|| {
quote! {
if body.is_some() {
return #refuse;
}
}
});
let forward = borrow.prepend(
repe,
borrow.child_call(
repe,
&field.ty,
ident,
quote! { tail, body },
quote! { out },
),
quote! { #key },
);
arms.push(quote! { #key => { #guard #forward } });
} else {
let span = field.ty.span();
let read = borrow.ok(if field.attrs.typed {
emit_typed_slice_spanned(span, quote! { self.#ident })
} else {
emit_value_spanned(span, quote! { self.#ident })
});
let write = match (field.attrs.readonly, borrow) {
(true, _) => quote! { Some(_) => #refuse, },
(false, Borrow::Exclusive) => quote_spanned! {span=>
Some(__repe_body) => {
__repe_body.read_into(#path, &mut self.#ident)?;
#ack
}
},
(false, Borrow::Shared) => quote! { Some(_) => None, },
};
arms.push(quote! {
#key => {
if !tail.is_empty() {
return #subpath;
}
match body {
None => #read,
#write
}
}
});
}
}
arms
}
#[derive(Clone, Copy)]
enum Borrow {
Exclusive,
Shared,
}
impl Borrow {
fn err(self, err: TokenStream2) -> TokenStream2 {
let refusal = self.refuse(err);
quote! { return #refusal; }
}
fn refuse(self, err: TokenStream2) -> TokenStream2 {
match self {
Borrow::Exclusive => quote! { Err(#err) },
Borrow::Shared => quote! { Some(Err(#err)) },
}
}
fn ok(self, expr: TokenStream2) -> TokenStream2 {
match self {
Borrow::Exclusive => expr,
Borrow::Shared => quote! { Some(#expr) },
}
}
fn child_call(
self,
repe: &TokenStream2,
ty: &Type,
ident: &Ident,
args: TokenStream2,
out: TokenStream2,
) -> TokenStream2 {
match self {
Borrow::Exclusive => quote! {
<#ty as #repe::RepeStruct>::repe_handle_into(
&mut self.#ident, #args, #out,
)
},
Borrow::Shared => quote! {
<#ty as #repe::RepeStruct>::repe_shared_into(
&self.#ident, #args, #out,
)
},
}
}
fn prepend(self, repe: &TokenStream2, call: TokenStream2, key: TokenStream2) -> TokenStream2 {
match self {
Borrow::Exclusive => quote! {
#call.map_err(|err| #repe::structs::prepend_path(err, #key))
},
Borrow::Shared => quote! {
#call.map(|__repe_result| {
__repe_result.map_err(|err| #repe::structs::prepend_path(err, #key))
})
},
}
}
fn accessor_call(self, repe: &TokenStream2, name: TokenStream2) -> TokenStream2 {
match self {
Borrow::Exclusive => quote! {
<Self as #repe::structs::RepeMethods>::repe_call_into(
self, &[#name], None, __repe_nested,
)
},
Borrow::Shared => quote! {
<Self as #repe::structs::RepeMethods>::repe_call_shared_into(
self, &[#name], None, __repe_nested,
)
},
}
}
fn entry_with(self, key: TokenStream2, produce: TokenStream2) -> TokenStream2 {
match self {
Borrow::Exclusive => quote! {
__repe_obj.entry_with(#key, |__repe_nested| { #produce })?;
},
Borrow::Shared => quote! {
if let Err(__repe_err) = __repe_obj.entry_try_with(#key, |__repe_nested| {
#produce
})? {
return Some(Err(__repe_err));
}
},
}
}
fn wrap(self, entries: &[TokenStream2], count: TokenStream2) -> TokenStream2 {
match self {
Borrow::Exclusive => quote! {
{
let mut __repe_obj = out.object(#count);
#(#entries)*
__repe_obj.finish();
Ok(())
}
},
Borrow::Shared => quote! {
{
let mut __repe_obj = out.object(#count);
#(#entries)*
__repe_obj.finish();
Some(Ok(()))
}
},
}
}
}
fn refuse_write(repe: &TokenStream2, borrow: Borrow) -> TokenStream2 {
borrow.refuse(quote! {
#repe::StructError::BodyUnexpected {
path: #repe::structs::path_from_segments(segments),
}
})
}
fn refuse_subpath(repe: &TokenStream2, borrow: Borrow) -> TokenStream2 {
borrow.refuse(quote! {
#repe::StructError::InvalidSubpath {
path: #repe::structs::path_from_segments(segments),
}
})
}
fn decode_method_args(
method: &MethodSpec,
bindings: &[Ident],
repe: &TokenStream2,
borrow: Borrow,
) -> TokenStream2 {
if method.args.is_empty() {
return quote! { let _ = &body; };
}
let path = endpoint_path(&method.endpoint);
let missing = borrow.err(quote! {
#repe::StructError::BodyExpected {
path: #repe::structs::path_from_segments(segments),
}
});
let take_body = quote! {
let __repe_body = match body {
Some(__repe_body) => __repe_body,
None => { #missing }
};
};
let bad_args = borrow.err(quote! { __repe_err });
if method.args.len() == 1 {
let binding = &bindings[0];
let ty = &method.args[0].1;
return quote! {
#take_body
let #binding: #ty = match __repe_body.read(#path) {
Ok(__repe_value) => __repe_value,
Err(__repe_err) => { #bad_args }
};
};
}
let names: Vec<LitStr> = method
.args
.iter()
.map(|(ident, _)| LitStr::new(&ident.to_string(), Span::call_site()))
.collect();
let decls = method.args.iter().zip(bindings).map(|((_, ty), binding)| {
let bad_args = &bad_args;
quote! {
let #binding: #ty = match __repe_args.next_arg() {
Ok(__repe_value) => __repe_value,
Err(__repe_err) => { #bad_args }
};
}
});
quote! {
#take_body
let mut __repe_args = match #repe::structs::MethodArgs::new(
#path, &[#(#names),*], __repe_body,
) {
Ok(__repe_args) => __repe_args,
Err(__repe_err) => { #bad_args }
};
#(#decls)*
}
}
fn build_method_arms(
methods: &[MethodSpec],
repe: &TokenStream2,
borrow: Borrow,
) -> Vec<TokenStream2> {
methods
.iter()
.map(|method| build_method_arm(method, repe, borrow))
.collect()
}
fn build_method_arm(method: &MethodSpec, repe: &TokenStream2, borrow: Borrow) -> TokenStream2 {
let key = LitStr::new(&method.endpoint, Span::call_site());
if matches!(borrow, Borrow::Shared) && !matches!(method.receiver, ReceiverKind::Ref) {
return quote! { #key => None, };
}
let path = endpoint_path(&method.endpoint);
let subpath = refuse_subpath(repe, borrow);
let method_ident = &method.method_ident;
let bindings: Vec<Ident> = (0..method.args.len())
.map(|i| format_ident!("__repe_arg{}", i))
.collect();
let decode_args = decode_method_args(method, &bindings, repe, borrow);
let emit_ok = if method.ret.ok_is_unit() {
emit_null()
} else {
emit_value(quote! { __repe_ok })
};
let invocation = quote_spanned! { method_ident.span()=>
Self::#method_ident(self #(, #bindings)*)
};
let call = borrow.ok(call_and_emit(invocation, &method.ret, emit_ok, repe, &path));
quote! {
#key => {
if !tail.is_empty() {
return #subpath;
}
#decode_args
#call
}
}
}
fn call_and_emit(
invocation: TokenStream2,
ret: &ReturnSpec,
emit_ok: TokenStream2,
repe: &TokenStream2,
path: &LitStr,
) -> TokenStream2 {
if ret.fallible {
let ok_pattern = if ret.ok_is_unit() {
quote! { Ok(_) }
} else {
quote! { Ok(__repe_ok) }
};
quote! {
match #invocation {
#ok_pattern => #emit_ok,
Err(__repe_err) => Err(#repe::StructError::Execution {
path: String::from(#path),
message: ::std::string::ToString::to_string(&__repe_err),
}),
}
}
} else if ret.ok_is_unit() {
quote! {
{
#invocation;
#emit_ok
}
}
} else {
quote! {
{
let __repe_ok = #invocation;
#emit_ok
}
}
}
}
fn build_accessor_arm(
accessor: &AccessorSpec,
repe: &TokenStream2,
borrow: Borrow,
) -> TokenStream2 {
let key = LitStr::new(&accessor.endpoint, Span::call_site());
let path = endpoint_path(&accessor.endpoint);
let subpath = refuse_subpath(repe, borrow);
let read = if matches!(borrow, Borrow::Shared)
&& !matches!(accessor.get.receiver, ReceiverKind::Ref)
{
quote! { None }
} else {
let getter = &accessor.get.method_ident;
let emit = if accessor.typed {
emit_typed_slice(quote! { __repe_ok })
} else {
emit_value(quote! { __repe_ok })
};
borrow.ok(call_and_emit(
quote! { Self::#getter(self) },
&accessor.get.ret,
emit,
repe,
&path,
))
};
let refuse = refuse_write(repe, borrow);
let write = match (&accessor.set, borrow) {
(None, _) => quote! { Some(_) => #refuse, },
(Some(_), Borrow::Shared) => quote! { Some(_) => None, },
(Some(set), Borrow::Exclusive) => {
let setter = &set.method_ident;
let ty = &set.args[0].1;
let call = call_and_emit(
quote! { Self::#setter(self, __repe_arg) },
&set.ret,
emit_null(),
repe,
&path,
);
quote! {
Some(__repe_body) => {
let __repe_arg: #ty = __repe_body.read(#path)?;
#call
}
}
}
};
quote! {
#key => {
if !tail.is_empty() {
return #subpath;
}
match body {
None => #read,
#write
}
}
}
}
fn shared_body_terms(
fields: &[FieldSpec],
struct_attrs: &StructAttrs,
from_impl_block: bool,
repe: &TokenStream2,
) -> Vec<TokenStream2> {
if struct_attrs.no_replace
|| struct_attrs
.methods
.iter()
.any(|m| matches!(m.receiver, ReceiverKind::Ref) && !m.args.is_empty())
{
return vec![quote! { true }];
}
let mut terms = Vec::new();
if from_impl_block {
terms.push(quote! {
<Self as #repe::structs::RepeMethods>::REPE_SHARED_SERVES_BODIES
});
}
for field in fields {
if field.attrs.skip {
continue;
}
if field.attrs.readonly {
return vec![quote! { true }];
}
if !field.attrs.nested {
continue;
}
let ty = &field.ty;
terms.push(quote! {
<#ty as #repe::RepeStruct>::REPE_SHARED_SERVES_BODIES
});
}
terms
}
fn listing_decline_terms(
fields: &[FieldSpec],
from_impl_block: bool,
repe: &TokenStream2,
) -> Vec<TokenStream2> {
let mut terms = Vec::new();
if from_impl_block {
terms.push(quote! {
<Self as #repe::structs::RepeMethods>::REPE_LISTING_NEEDS_EXCLUSIVE
});
}
for field in fields {
if field.attrs.skip || !field.attrs.nested {
continue;
}
let ident = &field.ident;
let ty = &field.ty;
terms.push(quote! {
<#ty as #repe::RepeStruct>::repe_listing_declines(&self.#ident)
});
}
terms
}
fn expand_methods(mut item_impl: ItemImpl) -> TokenStream2 {
let repe = repe_crate_path();
let mut stripped = Vec::new();
for item in &mut item_impl.items {
if let ImplItem::Fn(func) = item {
stripped.push(take_method_attrs(&mut func.attrs));
}
}
match collect_methods(&item_impl, stripped) {
Ok(published) => methods_impl(&item_impl, &published, &repe, false),
Err(err) => {
let error = err.to_compile_error();
let empty = methods_impl(&item_impl, &PublishedItems::default(), &repe, true);
quote! {
#error
#empty
}
}
}
}
enum Published {
Method,
Get { typed: bool },
Set,
}
struct AccessorSpec {
endpoint: String,
get: MethodSpec,
typed: bool,
set: Option<MethodSpec>,
}
#[derive(Default)]
struct PublishedItems {
methods: Vec<MethodSpec>,
accessors: Vec<AccessorSpec>,
}
fn reject_duplicate_accessor_half<'a>(
halves: &(impl Iterator<Item = &'a MethodSpec> + Clone),
key: &str,
) -> syn::Result<()> {
let mut seen: Vec<&str> = Vec::new();
for spec in halves.clone() {
if seen.contains(&spec.endpoint.as_str()) {
return Err(syn::Error::new(
spec.method_ident.span(),
format!(
"two methods claim `#[repe({key} = \"{endpoint}\")]`; a field-shaped \
endpoint has one read half and one write half, so one of these could never \
be called. Give one of them a different endpoint.",
endpoint = spec.endpoint
),
));
}
seen.push(&spec.endpoint);
}
Ok(())
}
fn collect_methods(
item_impl: &ItemImpl,
stripped: Vec<syn::Result<MethodAttrs>>,
) -> syn::Result<PublishedItems> {
if let Some((_, path, _)) = &item_impl.trait_ {
return Err(syn::Error::new_spanned(
path,
"`#[repe::methods]` applies to an inherent impl block, not a trait impl",
));
}
let mut methods: Vec<MethodSpec> = Vec::new();
let mut getters: Vec<(MethodSpec, bool)> = Vec::new();
let mut setters: Vec<MethodSpec> = Vec::new();
let mut stripped = stripped.into_iter();
for item in &item_impl.items {
let ImplItem::Fn(func) = item else {
continue;
};
let attrs = stripped
.next()
.expect("one parsed attribute set per impl fn")?;
if attrs.skip {
continue;
}
let Some((published, spec)) = parse_impl_method(&func.sig, &func.attrs, attrs)? else {
continue;
};
match published {
Published::Method => methods.push(spec),
Published::Get { typed } => getters.push((spec, typed)),
Published::Set => setters.push(spec),
}
}
reject_duplicate_accessor_half(&getters.iter().map(|(spec, _)| spec), "get")?;
reject_duplicate_accessor_half(&setters.iter(), "set")?;
let mut accessors: Vec<AccessorSpec> = Vec::new();
for (get, typed) in getters {
let set = setters
.iter()
.position(|spec| spec.endpoint == get.endpoint)
.map(|index| setters.remove(index));
accessors.push(AccessorSpec {
endpoint: get.endpoint.clone(),
get,
typed,
set,
});
}
if let Some(orphan) = setters.first() {
return Err(syn::Error::new(
orphan.method_ident.span(),
format!(
"`#[repe(set = \"{endpoint}\")]` has no matching \
`#[repe(get = \"{endpoint}\")]` in this block: a field-shaped endpoint that \
cannot be read has no value for the whole-struct listing to show. Add the read \
half, or publish this as an ordinary method.",
endpoint = orphan.endpoint
),
));
}
let endpoints: Vec<(&str, Span)> = methods
.iter()
.map(|spec| (spec.endpoint.as_str(), spec.method_ident.span()))
.chain(
accessors
.iter()
.map(|spec| (spec.endpoint.as_str(), spec.get.method_ident.span())),
)
.collect();
reject_duplicate_endpoints(&endpoints)?;
Ok(PublishedItems { methods, accessors })
}
fn methods_impl(
item_impl: &ItemImpl,
published: &PublishedItems,
repe: &TokenStream2,
recovered: bool,
) -> TokenStream2 {
let self_ty = &item_impl.self_ty;
let (impl_generics, _ty_generics, where_clause) = item_impl.generics.split_for_impl();
let signatures = published.methods.iter().map(|spec| {
let endpoint = LitStr::new(&spec.endpoint, Span::call_site());
let signature = LitStr::new(&spec.signature_display, Span::call_site());
quote! { (#endpoint, #signature) }
});
let accessor_endpoints = published
.accessors
.iter()
.map(|spec| LitStr::new(&spec.endpoint, Span::call_site()));
let listing_needs_exclusive = published
.accessors
.iter()
.any(|spec| !matches!(spec.get.receiver, ReceiverKind::Ref));
let shared_serves_bodies = published
.methods
.iter()
.any(|spec| matches!(spec.receiver, ReceiverKind::Ref) && !spec.args.is_empty())
|| published.accessors.iter().any(|spec| match &spec.set {
Some(set) => matches!(set.receiver, ReceiverKind::Ref),
None => true,
});
let mut bodies = Vec::new();
{
let arms = build_method_arms(&published.methods, repe, Borrow::Exclusive)
.into_iter()
.chain(
published
.accessors
.iter()
.map(|accessor| build_accessor_arm(accessor, repe, Borrow::Exclusive)),
)
.collect::<Vec<_>>();
bodies.push(quote! {
fn repe_call_into(
&mut self,
segments: &[&str],
body: Option<#repe::structs::RequestBody<'_>>,
out: &mut #repe::structs::ResponseBody<'_>,
) -> #repe::structs::StructResult<()> {
let Some((head, tail)) = segments.split_first() else {
return Err(#repe::StructError::InvalidPath { path: String::from("") });
};
let _ = (&out, tail, &body);
match *head {
#(#arms)*
_ => Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
}),
}
}
});
}
let shared_arms = build_method_arms(&published.methods, repe, Borrow::Shared)
.into_iter()
.chain(
published
.accessors
.iter()
.map(|accessor| build_accessor_arm(accessor, repe, Borrow::Shared)),
)
.collect::<Vec<_>>();
let shared_invalid_root = quote! {
Some(Err(#repe::StructError::InvalidPath { path: String::from("") }))
};
let shared_invalid_path = quote! {
Some(Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
}))
};
bodies.push(quote! {
fn repe_call_shared_into(
&self,
segments: &[&str],
body: Option<#repe::structs::RequestBody<'_>>,
out: &mut #repe::structs::ResponseBody<'_>,
) -> Option<#repe::structs::StructResult<()>> {
let Some((head, tail)) = segments.split_first() else {
return #shared_invalid_root;
};
let _ = (&out, tail, &body);
match *head {
#(#shared_arms)*
_ => #shared_invalid_path,
}
}
});
quote! {
#item_impl
impl #impl_generics #repe::structs::RepeMethods for #self_ty #where_clause {
const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)] =
&[#(#signatures),*];
const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] =
&[#(#accessor_endpoints),*];
const REPE_LISTING_NEEDS_EXCLUSIVE: bool = #listing_needs_exclusive;
const REPE_SHARED_SERVES_BODIES: bool = #shared_serves_bodies;
const REPE_TABLE_RECOVERED: bool = #recovered;
#(#bodies)*
}
}
}
#[derive(Default)]
struct MethodAttrs {
rename: Option<String>,
skip: bool,
get: Option<LitStr>,
set: Option<LitStr>,
typed: Option<Span>,
}
impl MethodAttrs {
fn accessor_endpoint(&self) -> Option<&LitStr> {
self.get.as_ref().or(self.set.as_ref())
}
}
fn take_method_attrs(attrs: &mut Vec<Attribute>) -> syn::Result<MethodAttrs> {
let mut parsed = MethodAttrs::default();
for attr in attrs.iter() {
if !attr.path().is_ident("repe") {
continue;
}
attr.parse_nested_meta(|meta| {
if parse_shared_meta(&meta, &mut parsed.rename, &mut parsed.skip)? {
return Ok(());
}
if meta.path.is_ident("get") {
parsed.get = Some(meta.value()?.parse()?);
return Ok(());
}
if meta.path.is_ident("set") {
parsed.set = Some(meta.value()?.parse()?);
return Ok(());
}
if meta.path.is_ident("typed") {
parsed.typed = Some(meta.path.span());
return Ok(());
}
Err(meta.error("unsupported `repe` method attribute"))
})?;
}
attrs.retain(|attr| !attr.path().is_ident("repe"));
validate_method_attrs(&parsed)?;
Ok(parsed)
}
fn validate_method_attrs(attrs: &MethodAttrs) -> syn::Result<()> {
if let (Some(get), Some(_)) = (&attrs.get, &attrs.set) {
return Err(syn::Error::new_spanned(
get,
"a method is either the `get` half of a field-shaped endpoint or the `set` half, not \
both: one takes no arguments and returns the value, the other takes the value and \
returns nothing",
));
}
let Some(endpoint) = attrs.accessor_endpoint() else {
if let Some(typed) = attrs.typed {
return Err(syn::Error::new(
typed,
"`#[repe(typed)]` applies to the `get` half of a field-shaped endpoint; an \
ordinary method's return value is always encoded as JSON",
));
}
return Ok(());
};
if attrs.skip {
return Err(syn::Error::new_spanned(
endpoint,
"`#[repe(skip)]` and `#[repe(get/set)]` contradict each other: one withholds the \
method from the served surface, the other publishes it",
));
}
if attrs.rename.is_some() {
return Err(syn::Error::new_spanned(
endpoint,
"`#[repe(rename = \"...\")]` has nothing to rename here: the endpoint of a \
field-shaped accessor is the name given to `get`/`set`",
));
}
if attrs.typed.is_some() && attrs.set.is_some() {
return Err(syn::Error::new_spanned(
endpoint,
"`#[repe(typed)]` describes how a value is *encoded* into a response, so it belongs \
on the `get` half; a `set` decodes whatever the client sent",
));
}
let value = endpoint.value();
if value.is_empty() {
return Err(syn::Error::new_spanned(
endpoint,
"a field-shaped endpoint needs a name",
));
}
if value.contains('/') {
return Err(syn::Error::new_spanned(
endpoint,
"a field-shaped endpoint is one path segment below the struct root, so it cannot \
contain `/`",
));
}
Ok(())
}
fn parse_impl_method(
sig: &Signature,
remaining_attrs: &[Attribute],
attrs: MethodAttrs,
) -> syn::Result<Option<(Published, MethodSpec)>> {
let Some(FnArg::Receiver(receiver)) = sig.inputs.first() else {
if let Some(endpoint) = attrs.accessor_endpoint() {
return Err(syn::Error::new_spanned(
endpoint,
"a field-shaped endpoint is served by a method on the instance, so its halves \
need a `&self` or `&mut self` receiver",
));
}
return Ok(None);
};
if let Some(cfg) = remaining_attrs
.iter()
.find(|attr| attr.path().is_ident("cfg") || attr.path().is_ident("cfg_attr"))
{
return Err(syn::Error::new_spanned(
cfg,
"`#[repe::methods]` cannot publish a conditionally-compiled method: `#[cfg]` is \
applied after this macro runs, so the endpoint would be generated even when the \
method is not. Move it to a plain `impl` block, or add `#[repe(skip)]` and expose \
an unconditional wrapper.",
));
}
if receiver.reference.is_none() {
return Err(syn::Error::new_spanned(
receiver,
"`#[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)",
));
}
let kind = if receiver.mutability.is_some() {
ReceiverKind::Mut
} else {
ReceiverKind::Ref
};
if sig.asyncness.is_some() {
return Err(syn::Error::new_spanned(
sig.asyncness,
"`#[repe::methods]` cannot publish an async method; the struct router dispatches synchronously (add `#[repe(skip)]` to exclude it)",
));
}
if sig.unsafety.is_some() {
return Err(syn::Error::new_spanned(
sig.unsafety,
"`#[repe::methods]` cannot publish an unsafe method (add `#[repe(skip)]` to exclude it)",
));
}
if let Some(variadic) = &sig.variadic {
return Err(syn::Error::new_spanned(
variadic,
"`#[repe::methods]` cannot publish a variadic method (add `#[repe(skip)]` to exclude it)",
));
}
if sig
.generics
.params
.iter()
.any(|param| !matches!(param, syn::GenericParam::Lifetime(_)))
{
return Err(syn::Error::new_spanned(
&sig.generics,
"`#[repe::methods]` cannot publish a generic method; the dispatch table needs one concrete signature (add `#[repe(skip)]` to exclude it)",
));
}
let mut args: Vec<(Ident, Type)> = Vec::new();
for (index, input) in sig.inputs.iter().skip(1).enumerate() {
let FnArg::Typed(pat_type) = input else {
continue;
};
if matches!(&*pat_type.ty, Type::Reference(_)) {
return Err(syn::Error::new_spanned(
&pat_type.ty,
"`#[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)",
));
}
if matches!(&*pat_type.ty, Type::ImplTrait(_)) {
return Err(syn::Error::new_spanned(
&pat_type.ty,
"`#[repe::methods]` needs a nameable argument type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
));
}
let name = match &*pat_type.pat {
syn::Pat::Ident(pat_ident) => pat_ident.ident.clone(),
_ => format_ident!("_{}", index),
};
args.push((name, (*pat_type.ty).clone()));
}
let ret_ty: Type = match &sig.output {
ReturnType::Default => syn::parse_quote! { () },
ReturnType::Type(_, ty) => (**ty).clone(),
};
if matches!(ret_ty, Type::ImplTrait(_)) {
return Err(syn::Error::new_spanned(
&sig.output,
"`#[repe::methods]` needs a nameable return type, not `impl Trait` (add `#[repe(skip)]` to exclude the method)",
));
}
let ret = classify_return(&ret_ty);
let signature_display = build_signature_string(kind, &args, &ret);
let (published, endpoint) = match (&attrs.get, &attrs.set) {
(Some(name), _) => {
if !args.is_empty() {
return Err(syn::Error::new_spanned(
&sig.inputs,
"the `get` half of a field-shaped endpoint takes no arguments: a client reads \
it the way it reads a field, with no request body to decode them from",
));
}
if ret.ok_is_unit() {
return Err(syn::Error::new_spanned(
&sig.output,
"the `get` half of a field-shaped endpoint has to return the value; a read \
that yields nothing has nothing to publish",
));
}
(
Published::Get {
typed: attrs.typed.is_some(),
},
name.value(),
)
}
(None, Some(name)) => {
if args.len() != 1 {
return Err(syn::Error::new_spanned(
&sig.inputs,
"the `set` half of a field-shaped endpoint takes exactly one argument: the \
request body *is* the new value, as it is for a field write",
));
}
if !ret.ok_is_unit() {
return Err(syn::Error::new_spanned(
&sig.output,
"the `set` half of a field-shaped endpoint returns nothing (or \
`Result<(), E>`): a field write is acknowledged with `null`, so a returned \
value would be silently dropped",
));
}
(Published::Set, name.value())
}
(None, None) => (
Published::Method,
attrs.rename.unwrap_or_else(|| sig.ident.to_string()),
),
};
Ok(Some((
published,
MethodSpec {
endpoint,
method_ident: sig.ident.clone(),
receiver: kind,
args,
ret,
signature_display,
},
)))
}
#[proc_macro_attribute]
pub fn plugin(attr: TokenStream, item: TokenStream) -> TokenStream {
let mut args = PluginArgs::default();
let parser = syn::meta::parser(|meta| args.parse(meta));
parse_macro_input!(attr with parser);
let item_fn = parse_macro_input!(item as syn::ItemFn);
match expand_plugin(args, item_fn) {
Ok(tokens) => tokens.into(),
Err(err) => err.to_compile_error().into(),
}
}
#[derive(Default)]
struct PluginArgs {
name: Option<LitStr>,
version: Option<LitStr>,
root: Option<LitStr>,
}
impl PluginArgs {
fn parse(&mut self, meta: ParseNestedMeta) -> syn::Result<()> {
if meta.path.is_ident("name") {
self.name = Some(meta.value()?.parse()?);
} else if meta.path.is_ident("version") {
self.version = Some(meta.value()?.parse()?);
} else if meta.path.is_ident("root") {
self.root = Some(meta.value()?.parse()?);
} else {
return Err(meta.error(
"unknown `#[repe::plugin]` argument; expected `root`, `name`, or `version`",
));
}
Ok(())
}
}
fn reject_interior_nul(field: &str, literal: &LitStr) -> syn::Result<()> {
if literal.value().contains('\0') {
return Err(syn::Error::new_spanned(
literal,
format!(
"`{field}` cannot contain a nul byte: it is handed to the host as a C string and \
would be truncated there"
),
));
}
Ok(())
}
fn expand_plugin(args: PluginArgs, item_fn: syn::ItemFn) -> syn::Result<TokenStream2> {
let repe = repe_crate_path();
let Some(root) = args.root else {
return Err(syn::Error::new(
Span::call_site(),
"`#[repe::plugin]` needs a `root` path prefix, e.g. \
`#[repe::plugin(root = \"/calculator\")]`",
));
};
reject_interior_nul("root", &root)?;
let root_value = root.value();
if !root_value.starts_with('/') {
return Err(syn::Error::new_spanned(
&root,
"`root` must be an absolute JSON Pointer prefix, so it has to start with `/`",
));
}
if root_value.len() > 1 && root_value.ends_with('/') {
return Err(syn::Error::new_spanned(
&root,
"`root` must not end with `/`: hosts prefix-match this against request paths, and the \
trailing separator is not part of the prefix",
));
}
let name = match &args.name {
Some(name) => {
reject_interior_nul("name", name)?;
quote! { #name }
}
None => quote! { env!("CARGO_PKG_NAME") },
};
let version = match &args.version {
Some(version) => {
reject_interior_nul("version", version)?;
quote! { #version }
}
None => quote! { env!("CARGO_PKG_VERSION") },
};
if !item_fn.sig.inputs.is_empty() {
return Err(syn::Error::new_spanned(
&item_fn.sig.inputs,
"`#[repe::plugin]` applies to a function taking no arguments: the host calls it \
through a C ABI that has nothing to pass",
));
}
if !item_fn.sig.generics.params.is_empty() {
return Err(syn::Error::new_spanned(
&item_fn.sig.generics,
"`#[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",
));
}
if item_fn.sig.asyncness.is_some() {
return Err(syn::Error::new_spanned(
&item_fn.sig,
"`#[repe::plugin]` cannot be applied to an `async fn`: `repe_plugin_call` is \
synchronous, with no runtime on the host side of the ABI to drive a future",
));
}
let build = &item_fn.sig.ident;
Ok(quote! {
#item_fn
#[doc(hidden)]
static __REPE_PLUGIN_INFO: #repe::plugin::RepePluginData = #repe::plugin::RepePluginData {
name: concat!(#name, "\0").as_ptr() as *const ::core::ffi::c_char,
version: concat!(#version, "\0").as_ptr() as *const ::core::ffi::c_char,
root_path: concat!(#root, "\0").as_ptr() as *const ::core::ffi::c_char,
};
#[doc(hidden)]
static __REPE_PLUGIN_RUNTIME: #repe::plugin::PluginRuntime =
#repe::plugin::PluginRuntime::new(#build);
#[unsafe(no_mangle)]
pub extern "C" fn repe_plugin_interface_version() -> ::core::primitive::u32 {
#repe::plugin::REPE_PLUGIN_INTERFACE_VERSION
}
#[unsafe(no_mangle)]
pub extern "C" fn repe_plugin_info() -> *const #repe::plugin::RepePluginData {
&__REPE_PLUGIN_INFO
}
#[unsafe(no_mangle)]
pub extern "C" fn repe_plugin_init() -> #repe::plugin::RepeResult {
__REPE_PLUGIN_RUNTIME.init()
}
#[unsafe(no_mangle)]
pub extern "C" fn repe_plugin_shutdown() {
__REPE_PLUGIN_RUNTIME.shutdown()
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn repe_plugin_call(
request: *const ::core::ffi::c_char,
request_size: ::core::primitive::u64,
) -> #repe::plugin::RepeBuffer {
unsafe { __REPE_PLUGIN_RUNTIME.call(request, request_size) }
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use syn::parse_quote;
fn field_error(field: syn::Field) -> String {
match parse_field(&field) {
Err(err) => err.to_string(),
Ok(spec) => panic!("`{}` was supposed to be rejected", spec.endpoint),
}
}
fn order(keys: &[&str]) -> ListingOrder {
ListingOrder {
keys: keys
.iter()
.map(|k| LitStr::new(k, Span::call_site()))
.collect(),
span: Span::call_site(),
}
}
fn declared(names: &[&str]) -> Vec<(&'static str, Span)> {
names
.iter()
.map(|n| {
(
&*Box::leak(n.to_string().into_boxed_str()),
Span::call_site(),
)
})
.collect()
}
#[test]
fn typed_and_nested_are_rejected_together() {
let msg = field_error(parse_quote! {
#[repe(typed, nested)]
child: Child
});
assert!(
msg.contains("BEVE typed array"),
"the message should say why the two cannot combine, got: {msg}"
);
}
#[test]
fn nested_serde_is_rejected_with_a_migration_note() {
for field in [
parse_quote! { #[repe(nested_serde)] child: Child },
parse_quote! { #[repe(typed, nested_serde)] child: Child },
parse_quote! { #[repe(nested, nested_serde)] child: Child },
] {
let msg = field_error(field);
assert!(
msg.contains("nested_serde") && msg.contains("structio"),
"the message should name what replaced it, got: {msg}"
);
}
}
#[test]
fn readonly_on_a_struct_is_rejected_and_points_at_no_replace() {
let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(readonly)] }];
let msg = match parse_struct_attrs(&attrs) {
Err(err) => err.to_string(),
Ok(_) => panic!("`readonly` on a struct is supposed to be rejected"),
};
assert!(
msg.contains("no_replace") && msg.contains("recursive"),
"the message should name the replacement and say why the two differ, got: {msg}"
);
}
#[test]
fn no_replace_on_a_struct_is_accepted() {
let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[repe(no_replace)] }];
let Ok(parsed) = parse_struct_attrs(&attrs) else {
panic!("`no_replace` is supposed to be accepted");
};
assert!(parsed.no_replace);
}
#[test]
fn readonly_on_a_field_is_still_accepted() {
let field: syn::Field = parse_quote! { #[repe(readonly)] a: u64 };
let Ok(spec) = parse_field(&field) else {
panic!("`readonly` on a field is supposed to be accepted");
};
assert!(spec.attrs.readonly);
}
#[test]
fn an_unknown_field_attribute_is_rejected() {
let msg = field_error(parse_quote! {
#[repe(nonsense)]
a: u64
});
assert!(
msg.contains("unsupported `repe` field attribute"),
"got: {msg}"
);
}
#[test]
fn the_ordinary_combinations_are_accepted() {
for field in [
parse_quote! { #[repe(typed)] values: Vec<f64> },
parse_quote! { #[repe(nested)] child: Child },
parse_quote! { #[repe(nested, readonly)] child: Child },
parse_quote! { #[repe(rename = "other")] a: u64 },
parse_quote! { #[repe(skip)] a: u64 },
] {
let field: syn::Field = field;
assert!(parse_field(&field).is_ok());
}
}
#[test]
fn an_order_naming_every_endpoint_is_accepted() {
let d = declared(&["a", "b"]);
assert!(validate_listing_order(&order(&["b", "a"]), &d, false).is_ok());
}
#[test]
fn a_key_named_twice_is_rejected() {
let d = declared(&["a"]);
let msg = validate_listing_order(&order(&["a", "a"]), &d, false)
.expect_err("a repeated key is rejected")
.to_string();
assert!(msg.contains("named twice"), "got: {msg}");
}
#[test]
fn a_key_that_is_not_an_endpoint_is_rejected() {
let d = declared(&["a"]);
let msg = validate_listing_order(&order(&["a", "typo"]), &d, false)
.expect_err("an unknown key is rejected")
.to_string();
assert!(
msg.contains("`typo` is not an endpoint on this struct"),
"the message should name the offending key, got: {msg}"
);
}
#[test]
fn an_endpoint_missing_from_the_order_is_rejected() {
let d = declared(&["a", "b"]);
let msg = validate_listing_order(&order(&["a"]), &d, false)
.expect_err("an omitted endpoint is rejected")
.to_string();
assert!(
msg.contains("`b` is missing from"),
"the message should name the omitted endpoint, got: {msg}"
);
}
#[test]
fn an_impl_block_defers_the_unknown_key_check_to_the_const_assertion() {
let d = declared(&["a"]);
assert!(validate_listing_order(&order(&["a", "calc"]), &d, true).is_ok());
let msg = validate_listing_order(&order(&["calc"]), &d, true)
.expect_err("a field omitted from the order is still rejected")
.to_string();
assert!(msg.contains("`a` is missing from"), "got: {msg}");
}
}