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()
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Sink {
Value,
Encode,
}
impl Sink {
fn emit_null(self) -> TokenStream2 {
match self {
Sink::Value => quote! { Ok(None) },
Sink::Encode => quote! {
{
out.write_null();
Ok(())
}
},
}
}
fn emit_value(self, repe: &TokenStream2, path: &LitStr, expr: TokenStream2) -> TokenStream2 {
match self {
Sink::Value => quote! {
{
let value = ::serde_json::to_value(&#expr)
.map_err(|source| #repe::StructError::Serialize {
path: String::from(#path),
source,
})?;
Ok(Some(value))
}
},
Sink::Encode => quote! { out.write(#path, &#expr) },
}
}
fn emit_typed_slice(
self,
repe: &TokenStream2,
path: &LitStr,
expr: TokenStream2,
) -> TokenStream2 {
match self {
Sink::Value => self.emit_value(repe, path, expr),
Sink::Encode => quote! { out.write_typed_slice(#path, &#expr[..]) },
}
}
fn struct_method(self) -> Ident {
match self {
Sink::Value => format_ident!("repe_handle"),
Sink::Encode => format_ident!("repe_handle_into"),
}
}
fn methods_method(self) -> Ident {
match self {
Sink::Value => format_ident!("repe_call"),
Sink::Encode => format_ident!("repe_call_into"),
}
}
fn with_out(self, args: TokenStream2) -> TokenStream2 {
match self {
Sink::Value => args,
Sink::Encode => quote! { #args, out },
}
}
}
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;
let handshake = from_impl_block.then(|| {
let declared: Vec<LitStr> = endpoints
.iter()
.map(|(endpoint, _)| LitStr::new(endpoint, Span::call_site()))
.collect();
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,
);
}
});
let mut bodies = Vec::new();
for sink in [Sink::Value, Sink::Encode] {
let listing = build_listing(
&field_specs,
&struct_attrs.methods,
from_impl_block,
&repe,
sink,
);
let field_arms = build_field_arms(&field_specs, &repe, sink);
let method_arms = build_method_arms(&struct_attrs.methods, &repe, sink);
let fallthrough = if from_impl_block {
let call = sink.methods_method();
let args = sink.with_out(quote! { self, segments, body });
quote! {
_ => <Self as #repe::structs::RepeMethods>::#call(#args),
}
} else {
quote! {
_ => Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
}),
}
};
let root_write_ack = sink.emit_null();
let (signature, ret) = match sink {
Sink::Value => (
quote! {
fn repe_handle(
&mut self,
segments: &[&str],
body: Option<::serde_json::Value>,
)
},
quote! { #repe::structs::StructResult<Option<::serde_json::Value>> },
),
Sink::Encode => (
quote! {
fn repe_handle_into(
&mut self,
segments: &[&str],
body: Option<::serde_json::Value>,
out: &mut #repe::structs::ResponseBody<'_>,
)
},
quote! { #repe::structs::StructResult<()> },
),
};
bodies.push(quote! {
#signature -> #ret {
if segments.is_empty() {
if let Some(value) = body {
*self = ::serde_json::from_value(value).map_err(|source| #repe::StructError::Deserialize {
path: String::from(""),
source,
})?;
return #root_write_ack;
}
return #listing;
}
let (head, tail) = segments.split_first().unwrap();
match *head {
#(#field_arms)*
#(#method_arms)*
#fallthrough
}
}
});
}
let read_listing =
build_read_listing(&field_specs, &struct_attrs.methods, from_impl_block, &repe);
let read_field_arms = build_read_field_arms(&field_specs, &repe);
let read_method_arms = build_read_method_arms(&struct_attrs.methods, &repe);
let read_fallthrough = if from_impl_block {
quote! {
_ => <Self as #repe::structs::RepeMethods>::repe_call_read_into(self, segments, out),
}
} else {
quote! {
_ => Some(Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
})),
}
};
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)||* }
};
bodies.push(quote! {
fn repe_listing_declines(&self) -> bool {
#listing_declines
}
});
bodies.push(quote! {
fn repe_read_into(
&self,
segments: &[&str],
out: &mut #repe::structs::ResponseBody<'_>,
) -> Option<#repe::structs::StructResult<()>> {
if segments.is_empty() {
return #read_listing;
}
let (head, tail) = segments.split_first().unwrap();
match *head {
#(#read_field_arms)*
#(#read_method_arms)*
#read_fallthrough
}
}
});
Ok(quote! {
impl #repe::RepeStruct for #struct_ident {
#(#bodies)*
}
#handshake
})
}
fn repe_crate_path() -> TokenStream2 {
match crate_name("repe") {
Ok(FoundCrate::Itself) => quote!(::repe),
Ok(FoundCrate::Name(name)) => {
let ident = Ident::new(&name, Span::call_site());
quote!(::#ident)
}
Err(_) => quote!(::repe),
}
}
fn reject_duplicate_endpoints(endpoints: &[(&str, Span)]) -> syn::Result<()> {
for (index, (name, _)) in endpoints.iter().enumerate() {
if let Some((_, span)) = endpoints[..index].iter().find(|(prior, _)| prior == name) {
let _ = span;
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("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,
}
fn parse_struct_attrs(attrs: &[Attribute]) -> syn::Result<StructAttrs> {
let mut methods = Vec::new();
let mut methods_from_impl_block = false;
for attr in attrs {
if !attr.path().is_ident("repe") {
continue;
}
attr.parse_nested_meta(|meta| {
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,
})
}
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("& '", "&'")
}
fn build_listing(
fields: &[FieldSpec],
methods: &[MethodSpec],
from_impl_block: bool,
repe: &TokenStream2,
sink: Sink,
) -> TokenStream2 {
let mut entries = Vec::new();
for field in fields {
if field.attrs.skip {
continue;
}
let key = LitStr::new(&field.endpoint, Span::call_site());
let ident = &field.ident;
if field.attrs.nested {
let ty = &field.ty;
let method = sink.struct_method();
entries.push(match sink {
Sink::Value => quote! {
{
let nested = <#ty as #repe::RepeStruct>::#method(&mut self.#ident, &[], None)
.map_err(|err| #repe::structs::prepend_path(err, #key))?;
map.insert(String::from(#key), nested.unwrap_or(::serde_json::Value::Null));
}
},
Sink::Encode => quote! {
__repe_obj.entry_with(#key, |__repe_nested| {
<#ty as #repe::RepeStruct>::#method(&mut self.#ident, &[], None, __repe_nested)
.map_err(|err| #repe::structs::prepend_path(err, #key))
})?;
},
});
} else {
let path = LitStr::new(&format!("/{}", field.endpoint), Span::call_site());
entries.push(match sink {
Sink::Value => quote! {
{
let value = ::serde_json::to_value(&self.#ident)
.map_err(|source| #repe::StructError::Serialize {
path: String::from(#path),
source,
})?;
map.insert(String::from(#key), value);
}
},
Sink::Encode => quote! { __repe_obj.entry(#key, &self.#ident)?; },
});
}
}
for method in methods {
let key = LitStr::new(&method.endpoint, Span::call_site());
let signature = LitStr::new(&method.signature_display, Span::call_site());
entries.push(match sink {
Sink::Value => quote! {
map.insert(
String::from(#key),
::serde_json::Value::String(String::from(#signature)),
);
},
Sink::Encode => quote! { __repe_obj.entry(#key, &#signature)?; },
});
}
if from_impl_block {
entries.push(match sink {
Sink::Value => quote! {
for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
map.insert(String::from(name), ::serde_json::Value::String(String::from(signature)));
}
},
Sink::Encode => quote! {
for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
__repe_obj.entry(name, &signature)?;
}
},
});
entries.push(match sink {
Sink::Value => quote! {
for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
let value = <Self as #repe::structs::RepeMethods>::repe_call(self, &[name], None)?;
map.insert(
String::from(name),
value.unwrap_or(::serde_json::Value::Null),
);
}
},
Sink::Encode => quote! {
for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
__repe_obj.entry_with(name, |__repe_nested| {
<Self as #repe::structs::RepeMethods>::repe_call_into(
self, &[name], None, __repe_nested,
)
})?;
}
},
});
}
match sink {
Sink::Value => quote! {
{
let mut map = ::serde_json::Map::new();
#(#entries)*
Ok(Some(::serde_json::Value::Object(map)))
}
},
Sink::Encode => quote! {
{
let mut __repe_obj = out.object();
#(#entries)*
__repe_obj.finish();
Ok(())
}
},
}
}
fn nested_dispatch(
ty: &Type,
ident: &Ident,
key: LitStr,
args: TokenStream2,
repe: &TokenStream2,
sink: Sink,
) -> TokenStream2 {
let method = sink.struct_method();
let args = sink.with_out(quote! { &mut self.#ident, #args });
quote! {
<#ty as #repe::RepeStruct>::#method(#args)
.map_err(|err| #repe::structs::prepend_path(err, #key))
}
}
fn build_field_arms(fields: &[FieldSpec], repe: &TokenStream2, sink: Sink) -> Vec<TokenStream2> {
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 = LitStr::new(&format!("/{}", field.endpoint), Span::call_site());
let write = if field.attrs.readonly {
quote! {
Some(_) => Err(#repe::StructError::BodyUnexpected {
path: #repe::structs::path_from_segments(segments),
}),
}
} else {
let ack = sink.emit_null();
quote! {
Some(value) => {
self.#ident = ::serde_json::from_value(value)
.map_err(|source| #repe::StructError::Deserialize {
path: String::from(#path),
source,
})?;
#ack
}
}
};
if field.attrs.nested {
let descend = nested_dispatch(
&field.ty,
ident,
key.clone(),
quote! { tail, body },
repe,
sink,
);
let whole = nested_dispatch(
&field.ty,
ident,
key.clone(),
quote! { &[], None },
repe,
sink,
);
let read = match sink {
Sink::Value => quote! {
{
let nested = #whole?;
Ok(Some(nested.unwrap_or(::serde_json::Value::Null)))
}
},
Sink::Encode => whole,
};
arms.push(quote! {
#key => {
if tail.is_empty() {
return match body {
None => #read,
#write
};
} else {
return #descend;
}
}
});
} else {
let read = if field.attrs.typed {
sink.emit_typed_slice(repe, &path, quote! { self.#ident })
} else {
sink.emit_value(repe, &path, quote! { self.#ident })
};
arms.push(quote! {
#key => {
if !tail.is_empty() {
return Err(#repe::StructError::InvalidSubpath {
path: #repe::structs::path_from_segments(segments),
});
}
return match body {
None => #read,
#write
};
}
});
}
}
arms
}
fn build_method_arms(methods: &[MethodSpec], repe: &TokenStream2, sink: Sink) -> Vec<TokenStream2> {
methods
.iter()
.map(|method| build_method_arm(method, repe, sink))
.collect()
}
fn build_method_arm(method: &MethodSpec, repe: &TokenStream2, sink: Sink) -> TokenStream2 {
let key = LitStr::new(&method.endpoint, Span::call_site());
let path = LitStr::new(&format!("/{}", method.endpoint), Span::call_site());
let method_ident = &method.method_ident;
let bindings: Vec<Ident> = (0..method.args.len())
.map(|i| format_ident!("__repe_arg{}", i))
.collect();
let take_body = quote! {
let value = match body {
Some(value) => value,
None => {
return Err(#repe::StructError::BodyExpected {
path: #repe::structs::path_from_segments(segments),
});
}
};
};
let decode_args = match method.args.len() {
0 => quote! { let _ = &body; },
1 => {
let binding = &bindings[0];
let ty = &method.args[0].1;
quote! {
#take_body
let #binding: #ty = ::serde_json::from_value(value).map_err(|source| #repe::StructError::Deserialize {
path: String::from(#path),
source,
})?;
}
}
_ => {
let names: Vec<LitStr> = method
.args
.iter()
.map(|(ident, _)| LitStr::new(&ident.to_string(), Span::call_site()))
.collect();
let decls = bindings
.iter()
.zip(method.args.iter())
.map(|(binding, (_, ty))| quote! { let #binding: #ty = __repe_args.next_arg()?; });
quote! {
#take_body
let mut __repe_args = #repe::structs::MethodArgs::new(#path, &[#(#names),*], value)?;
#(#decls)*
}
}
};
let ok_is_unit = method.ret.ok_is_unit();
let emit_ok = if ok_is_unit {
sink.emit_null()
} else {
sink.emit_value(repe, &path, quote! { __repe_ok })
};
let call_and_emit = call_and_emit(
quote! { Self::#method_ident(self #(, #bindings)*) },
&method.ret,
emit_ok,
repe,
&path,
);
quote! {
#key => {
if !tail.is_empty() {
return Err(#repe::StructError::InvalidSubpath {
path: #repe::structs::path_from_segments(segments),
});
}
#decode_args
#call_and_emit
}
}
}
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, sink: Sink) -> TokenStream2 {
let key = LitStr::new(&accessor.endpoint, Span::call_site());
let path = LitStr::new(&format!("/{}", accessor.endpoint), Span::call_site());
let getter = &accessor.get.method_ident;
let emit = if accessor.typed {
sink.emit_typed_slice(repe, &path, quote! { __repe_ok })
} else {
sink.emit_value(repe, &path, quote! { __repe_ok })
};
let read = call_and_emit(
quote! { Self::#getter(self) },
&accessor.get.ret,
emit,
repe,
&path,
);
let write = match &accessor.set {
None => quote! {
Some(_) => Err(#repe::StructError::BodyUnexpected {
path: #repe::structs::path_from_segments(segments),
}),
},
Some(set) => {
let setter = &set.method_ident;
let ty = &set.args[0].1;
let call = call_and_emit(
quote! { Self::#setter(self, __repe_arg) },
&set.ret,
sink.emit_null(),
repe,
&path,
);
quote! {
Some(value) => {
let __repe_arg: #ty = ::serde_json::from_value(value)
.map_err(|source| #repe::StructError::Deserialize {
path: String::from(#path),
source,
})?;
#call
}
}
}
};
quote! {
#key => {
if !tail.is_empty() {
return Err(#repe::StructError::InvalidSubpath {
path: #repe::structs::path_from_segments(segments),
});
}
match body {
None => #read,
#write
}
}
}
}
fn read_invalid_subpath(repe: &TokenStream2) -> TokenStream2 {
quote! {
Some(Err(#repe::StructError::InvalidSubpath {
path: #repe::structs::path_from_segments(segments),
}))
}
}
fn build_read_call_arm(
endpoint: &str,
receiver: ReceiverKind,
invocation: TokenStream2,
ret: &ReturnSpec,
typed: bool,
repe: &TokenStream2,
) -> TokenStream2 {
let key = LitStr::new(endpoint, Span::call_site());
if !matches!(receiver, ReceiverKind::Ref) {
return quote! { #key => None, };
}
let path = LitStr::new(&format!("/{endpoint}"), Span::call_site());
let emit_ok = if ret.ok_is_unit() {
Sink::Encode.emit_null()
} else if typed {
Sink::Encode.emit_typed_slice(repe, &path, quote! { __repe_ok })
} else {
Sink::Encode.emit_value(repe, &path, quote! { __repe_ok })
};
let call = call_and_emit(invocation, ret, emit_ok, repe, &path);
let subpath = read_invalid_subpath(repe);
quote! {
#key => {
if !tail.is_empty() {
return #subpath;
}
Some(#call)
}
}
}
fn build_read_field_arms(fields: &[FieldSpec], repe: &TokenStream2) -> Vec<TokenStream2> {
let subpath = read_invalid_subpath(repe);
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 = LitStr::new(&format!("/{}", field.endpoint), Span::call_site());
if field.attrs.nested {
let ty = &field.ty;
arms.push(quote! {
#key => <#ty as #repe::RepeStruct>::repe_read_into(&self.#ident, tail, out)
.map(|__repe_result| {
__repe_result.map_err(|err| #repe::structs::prepend_path(err, #key))
}),
});
} else {
let read = if field.attrs.typed {
Sink::Encode.emit_typed_slice(repe, &path, quote! { self.#ident })
} else {
Sink::Encode.emit_value(repe, &path, quote! { self.#ident })
};
arms.push(quote! {
#key => {
if !tail.is_empty() {
return #subpath;
}
Some(#read)
}
});
}
}
arms
}
fn build_read_method_arms(methods: &[MethodSpec], repe: &TokenStream2) -> Vec<TokenStream2> {
methods
.iter()
.map(|method| {
if !method.args.is_empty() {
let key = LitStr::new(&method.endpoint, Span::call_site());
return quote! { #key => None, };
}
let method_ident = &method.method_ident;
let invocation = quote_spanned! { method_ident.span()=>
Self::#method_ident(self)
};
build_read_call_arm(
&method.endpoint,
method.receiver,
invocation,
&method.ret,
false,
repe,
)
})
.collect()
}
fn build_read_accessor_arm(accessor: &AccessorSpec, repe: &TokenStream2) -> TokenStream2 {
let getter = &accessor.get.method_ident;
build_read_call_arm(
&accessor.endpoint,
accessor.get.receiver,
quote! { Self::#getter(self) },
&accessor.get.ret,
accessor.typed,
repe,
)
}
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 build_read_listing(
fields: &[FieldSpec],
methods: &[MethodSpec],
from_impl_block: bool,
repe: &TokenStream2,
) -> TokenStream2 {
let guard = (!listing_decline_terms(fields, from_impl_block, repe).is_empty()).then(|| {
quote! {
if <Self as #repe::RepeStruct>::repe_listing_declines(self) {
return None;
}
}
});
let mut entries = Vec::new();
for field in fields {
if field.attrs.skip {
continue;
}
let key = LitStr::new(&field.endpoint, Span::call_site());
let ident = &field.ident;
if field.attrs.nested {
let ty = &field.ty;
entries.push(quote! {
if let Err(__repe_err) = __repe_obj.entry_try_with(#key, |__repe_nested| {
<#ty as #repe::RepeStruct>::repe_read_into(&self.#ident, &[], __repe_nested)
.map(|__repe_result| {
__repe_result.map_err(|err| #repe::structs::prepend_path(err, #key))
})
})? {
return Some(Err(__repe_err));
}
});
} else {
entries.push(quote! {
if let Err(__repe_err) = __repe_obj.entry(#key, &self.#ident) {
return Some(Err(__repe_err));
}
});
}
}
for method in methods {
let key = LitStr::new(&method.endpoint, Span::call_site());
let signature = LitStr::new(&method.signature_display, Span::call_site());
entries.push(quote! {
if let Err(__repe_err) = __repe_obj.entry(#key, &#signature) {
return Some(Err(__repe_err));
}
});
}
if from_impl_block {
entries.push(quote! {
for &(name, signature) in <Self as #repe::structs::RepeMethods>::REPE_METHOD_SIGNATURES {
if let Err(__repe_err) = __repe_obj.entry(name, &signature) {
return Some(Err(__repe_err));
}
}
});
entries.push(quote! {
for &name in <Self as #repe::structs::RepeMethods>::REPE_ACCESSOR_ENDPOINTS {
if let Err(__repe_err) = __repe_obj.entry_try_with(name, |__repe_nested| {
<Self as #repe::structs::RepeMethods>::repe_call_read_into(
self, &[name], __repe_nested,
)
})? {
return Some(Err(__repe_err));
}
}
});
}
quote! {
{
#guard
let mut __repe_obj = out.object();
#(#entries)*
__repe_obj.finish();
Some(Ok(()))
}
}
}
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),
Err(err) => {
let error = err.to_compile_error();
let empty = methods_impl(&item_impl, &PublishedItems::default(), &repe);
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,
) -> 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 mut bodies = Vec::new();
for sink in [Sink::Value, Sink::Encode] {
let arms = build_method_arms(&published.methods, repe, sink)
.into_iter()
.chain(
published
.accessors
.iter()
.map(|accessor| build_accessor_arm(accessor, repe, sink)),
)
.collect::<Vec<_>>();
let (signature, ret, unused) = match sink {
Sink::Value => (
quote! {
fn repe_call(
&mut self,
segments: &[&str],
body: Option<::serde_json::Value>,
)
},
quote! { #repe::structs::StructResult<Option<::serde_json::Value>> },
quote! { let _ = &body; },
),
Sink::Encode => (
quote! {
fn repe_call_into(
&mut self,
segments: &[&str],
body: Option<::serde_json::Value>,
out: &mut #repe::structs::ResponseBody<'_>,
)
},
quote! { #repe::structs::StructResult<()> },
quote! { let _ = &body; let _ = &out; },
),
};
bodies.push(quote! {
#signature -> #ret {
let Some((head, tail)) = segments.split_first() else {
return Err(#repe::StructError::InvalidPath { path: String::from("") });
};
#unused
match *head {
#(#arms)*
_ => Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
}),
}
}
});
}
let read_arms = build_read_method_arms(&published.methods, repe)
.into_iter()
.chain(
published
.accessors
.iter()
.map(|accessor| build_read_accessor_arm(accessor, repe)),
)
.collect::<Vec<_>>();
let read_invalid_root = quote! {
Some(Err(#repe::StructError::InvalidPath { path: String::from("") }))
};
let read_invalid_path = quote! {
Some(Err(#repe::StructError::InvalidPath {
path: #repe::structs::path_from_segments(segments),
}))
};
bodies.push(quote! {
fn repe_call_read_into(
&self,
segments: &[&str],
out: &mut #repe::structs::ResponseBody<'_>,
) -> Option<#repe::structs::StructResult<()>> {
let Some((head, tail)) = segments.split_first() else {
return #read_invalid_root;
};
let _ = (&out, tail);
match *head {
#(#read_arms)*
_ => #read_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;
#(#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) }
}
})
}