rust-nex/macros/src/lib.rs

576 lines
18 KiB
Rust
Raw Normal View History

2025-03-23 10:54:01 +01:00
mod protos;
extern crate proc_macro;
2025-06-29 11:40:42 +02:00
use crate::protos::{ProtoMethodData, RmcProtocolData};
use proc_macro::TokenStream;
2025-06-29 11:40:42 +02:00
use proc_macro2::{Ident, Literal, Span};
use quote::{quote, TokenStreamExt};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
2025-06-29 11:40:42 +02:00
use syn::{
2026-04-25 14:24:33 +02:00
parse_macro_input, Attribute, Data, DataStruct, DeriveInput, Fields, FnArg, Lit, LitInt,
LitStr, Pat, Token, TraitItem,
2025-06-29 11:40:42 +02:00
};
2025-03-08 00:56:44 +01:00
2025-06-29 11:40:42 +02:00
struct ProtoInputParams {
2025-03-08 00:56:44 +01:00
proto_num: LitInt,
2025-06-29 11:40:42 +02:00
properties: Option<(Token![,], Punctuated<Ident, Token![,]>)>,
2025-03-08 00:56:44 +01:00
}
2025-06-29 11:40:42 +02:00
impl Parse for ProtoInputParams {
2025-03-08 00:56:44 +01:00
fn parse(input: ParseStream) -> syn::Result<Self> {
let proto_num = input.parse()?;
2025-06-29 11:40:42 +02:00
if let Some(seperator) = input.parse()? {
2025-03-08 00:56:44 +01:00
let mut punctuated = Punctuated::new();
loop {
2025-06-29 11:40:42 +02:00
punctuated.push_value(input.parse()?);
2025-03-08 00:56:44 +01:00
if let Some(punct) = input.parse()? {
punctuated.push_punct(punct);
} else {
2025-06-29 11:40:42 +02:00
return Ok(Self {
proto_num,
properties: Some((seperator, punctuated)),
});
2025-03-08 00:56:44 +01:00
}
}
} else {
2025-06-29 11:40:42 +02:00
Ok(Self {
proto_num,
properties: None,
})
2025-03-08 00:56:44 +01:00
}
}
}
2025-06-29 11:40:42 +02:00
fn gen_serialize_data_struct(
s: DataStruct,
struct_attr: Option<&Attribute>,
2026-03-24 15:48:56 +01:00
) -> (
proc_macro2::TokenStream,
proc_macro2::TokenStream,
proc_macro2::TokenStream,
) {
let serialize_base_content = {
let mut serialize_content = quote! {};
2025-06-29 11:40:42 +02:00
for f in &s.fields {
if f.attrs.iter().any(|a| {
a.path().segments.len() == 1
&& a.path()
.segments
.first()
.is_some_and(|p| p.ident.to_string() == "extends")
}) {
continue;
}
let ident = f.ident.as_ref().unwrap();
2025-06-29 11:40:42 +02:00
serialize_content.append_all(quote! {
2025-09-21 15:59:27 +02:00
rnex_core::rmc::structures::RmcSerialize::serialize(&self.#ident, writer)?;
})
}
2025-06-29 11:40:42 +02:00
quote! {
#serialize_content
Ok(())
}
};
let struct_ctor = {
let mut structure_content = quote! {};
for f in &s.fields {
let ident = f.ident.as_ref().unwrap();
2025-06-29 11:40:42 +02:00
structure_content.append_all(quote! {#ident, });
}
2025-06-29 11:40:42 +02:00
quote! {
Ok(Self{
#structure_content
})
}
};
let deserialize_base_content = {
let mut deserialize_content = quote! {};
2025-06-29 11:40:42 +02:00
for f in &s.fields {
if f.attrs.iter().any(|a| {
a.path().segments.len() == 1
&& a.path()
.segments
.first()
.is_some_and(|p| p.ident.to_string() == "extends")
}) {
continue;
}
let ident = f.ident.as_ref().unwrap();
let ty = &f.ty;
2025-06-29 11:40:42 +02:00
deserialize_content.append_all(quote! {
let #ident = <#ty> :: deserialize(reader)?;
})
}
2025-06-29 11:40:42 +02:00
quote! {
#deserialize_content
#struct_ctor
}
};
2025-11-12 22:41:34 +01:00
let write_size = {
let mut size_content = quote! { 0 };
for f in &s.fields {
let ident = f.ident.as_ref().unwrap();
size_content.append_all(quote! {
+ rnex_core::rmc::structures::RmcSerialize::serialize_write_size(&self.#ident)?
})
}
size_content
};
let write_size = if let Some(_) = struct_attr {
2026-03-24 15:48:56 +01:00
quote! { #write_size + if rnex_core::config::FEATURE_HAS_STRUCT_HEADER{ 5 } else { 0 } }
2025-11-12 22:41:34 +01:00
} else {
write_size
};
2025-02-06 17:54:38 +01:00
// generate base with extends stuff
2025-06-29 11:40:42 +02:00
let serialize_base_content = if let Some(attr) = struct_attr {
let version: Literal = attr.parse_args().expect("has to be a literal");
let pre_inner = if let Some(f) = s.fields.iter().find(|f| {
2025-06-29 11:40:42 +02:00
f.attrs.iter().any(|a| {
a.path().segments.len() == 1
&& a.path()
.segments
.first()
.is_some_and(|p| p.ident.to_string() == "extends")
})
}) {
let ident = f.ident.as_ref().unwrap();
quote! {
self.#ident.serialize(writer)?;
}
} else {
quote! {}
};
quote! {
#pre_inner
2025-11-12 22:41:34 +01:00
rnex_core::rmc::structures::rmc_struct::write_struct(
writer,
#version,
rnex_core::rmc::structures::helpers::len_of_write(
|writer|{
#serialize_base_content
}
),
|writer|{
#serialize_base_content
}
)?;
Ok(())
}
} else {
serialize_base_content
};
2025-06-29 11:40:42 +02:00
let deserialize_base_content = if let Some(attr) = struct_attr {
let version: Literal = attr.parse_args().expect("has to be a literal");
let pre_inner = if let Some(f) = s.fields.iter().find(|f| {
2025-06-29 11:40:42 +02:00
f.attrs.iter().any(|a| {
a.path().segments.len() == 1
&& a.path()
.segments
.first()
.is_some_and(|p| p.ident.to_string() == "extends")
})
}) {
let ident = f.ident.as_ref().unwrap();
let ty = &f.ty;
quote! {
let #ident = <#ty> :: deserialize(reader)?;
}
} else {
quote! {}
};
quote! {
#pre_inner
2025-09-21 15:59:27 +02:00
Ok(rnex_core::rmc::structures::rmc_struct::read_struct(reader, #version, move |mut reader|{
#deserialize_base_content
})?)
}
} else {
deserialize_base_content
};
2026-03-24 15:48:56 +01:00
let write_size = quote! {
2025-11-12 22:41:34 +01:00
fn serialize_write_size(&self) -> rnex_core::rmc::structures::Result<u32>{
Ok(#write_size)
}
};
(serialize_base_content, deserialize_base_content, write_size)
2025-06-29 11:40:42 +02:00
}
#[proc_macro_derive(RmcSerialize, attributes(extends, rmc_struct))]
pub fn rmc_serialize(input: TokenStream) -> TokenStream {
let derive_input = parse_macro_input!(input as DeriveInput);
let struct_attr = derive_input.attrs.iter().find(|a| {
a.path().segments.len() == 1
&& a.path()
.segments
.first()
.is_some_and(|p| p.ident.to_string() == "rmc_struct")
});
let repr_attr = derive_input.attrs.iter().find(|a| {
a.path().segments.len() == 1
&& a.path()
.segments
.first()
.is_some_and(|p| p.ident.to_string() == "repr")
});
/*let Data::Struct(s) = derive_input.data else {
panic!("rmc struct type MUST be a struct");
};*/
2025-11-12 22:41:34 +01:00
let (serialize_base_content, deserialize_base_content, write_size) = match derive_input.data {
2025-06-29 11:40:42 +02:00
Data::Struct(s) => gen_serialize_data_struct(s, struct_attr),
Data::Enum(e) => {
let Some(repr_attr) = repr_attr else {
panic!("missing repr attribute");
};
let ty: Ident = repr_attr.parse_args().unwrap();
let mut inner_match_de = quote! {};
let mut inner_match_se = quote! {};
2025-11-13 10:06:58 +01:00
//let mut inner_match_len = quote!{};
2025-06-29 11:40:42 +02:00
for variant in e.variants {
let Some((_, val)) = variant.discriminant else {
panic!("missing discriminant");
};
let field_data_de = match &variant.fields {
Fields::Named(v) => {
let mut base = quote! {};
for field in v.named.iter() {
let ty = &field.ty;
let name = &field.ident;
base.append_all(quote!{
2025-09-21 15:59:27 +02:00
#name: <#ty as rnex_core::rmc::structures::RmcSerialize>::deserialize(reader)?,
2025-06-29 11:40:42 +02:00
});
}
quote! {{#base}}
}
Fields::Unnamed(n) => {
let mut base = quote! {};
for field in n.unnamed.iter() {
let ty = &field.ty;
base.append_all(quote!{
2025-09-21 15:59:27 +02:00
<#ty as rnex_core::rmc::structures::RmcSerialize>::deserialize(reader)?,
2025-06-29 11:40:42 +02:00
});
}
quote! {(#base)}
}
Fields::Unit => {
quote! {}
}
};
let mut se_with_fields = quote! {
2025-09-21 15:59:27 +02:00
<#ty as rnex_core::rmc::structures::RmcSerialize>::serialize(&#val, writer)?;
2025-06-29 11:40:42 +02:00
};
match &variant.fields {
Fields::Named(v) => {
for field in v.named.iter() {
let ty = &field.ty;
let name = &field.ident;
se_with_fields.append_all(quote!{
2025-09-21 15:59:27 +02:00
<#ty as rnex_core::rmc::structures::RmcSerialize>::serialize(#name ,writer)?;
2025-06-29 11:40:42 +02:00
});
}
}
Fields::Unnamed(n) => {
for (i, field) in n.unnamed.iter().enumerate() {
let ty = &field.ty;
let ident = Ident::new(&format!("val_{}", i), Span::call_site());
se_with_fields.append_all(quote!{
2025-09-21 15:59:27 +02:00
<#ty as rnex_core::rmc::structures::RmcSerialize>::serialize(#ident, writer)?;
2025-06-29 11:40:42 +02:00
});
}
}
Fields::Unit => {}
};
let field_match_se = match &variant.fields {
Fields::Named(v) => {
let mut base = quote! {};
for field in v.named.iter() {
let name = &field.ident;
base.append_all(quote! {
#name,
});
}
quote! {{#base}}
}
Fields::Unnamed(n) => {
let mut base = quote! {};
for (i, _field) in n.unnamed.iter().enumerate() {
let ident = Ident::new(&format!("val_{}", i), Span::call_site());
base.append_all(quote! {
#ident,
});
}
quote! {(#base)}
}
Fields::Unit => {
quote! {}
}
};
let name = variant.ident;
inner_match_de.append_all(quote! {
#val => Self::#name #field_data_de,
});
inner_match_se.append_all(quote! {
Self::#name #field_match_se => {
#se_with_fields
},
});
}
let serialize_base_content = quote! {
match self{
#inner_match_se
};
Ok(())
};
let deserialize_base_content = quote! {
2025-09-21 15:59:27 +02:00
let val: Self = match <#ty as rnex_core::rmc::structures::RmcSerialize>::deserialize(reader)?{
2025-06-29 11:40:42 +02:00
#inner_match_de
2025-09-21 15:59:27 +02:00
v => return Err(rnex_core::rmc::structures::Error::UnexpectedValue(v as _))
2025-06-29 11:40:42 +02:00
};
Ok(val)
};
2026-03-24 15:48:56 +01:00
(serialize_base_content, deserialize_base_content, quote! {})
2025-06-29 11:40:42 +02:00
}
Data::Union(_) => {
unimplemented!()
}
};
// generate base data
2026-04-25 14:24:33 +02:00
let str_name = Lit::Str(LitStr::new(
&derive_input.ident.to_string(),
derive_input.ident.span(),
));
let ident = derive_input.ident;
let tokens = quote! {
2025-09-21 15:59:27 +02:00
impl rnex_core::rmc::structures::RmcSerialize for #ident{
2025-11-12 22:41:34 +01:00
#[inline(always)]
fn serialize(&self, writer: &mut impl ::std::io::Write) -> rnex_core::rmc::structures::Result<()>{
#serialize_base_content
}
2025-11-12 22:41:34 +01:00
#[inline(always)]
fn deserialize(reader: &mut impl ::std::io::Read) -> rnex_core::rmc::structures::Result<Self>{
#deserialize_base_content
}
2025-11-12 22:41:34 +01:00
#write_size
2026-04-25 14:24:33 +02:00
fn name() -> &'static str{
#str_name
}
}
};
tokens.into()
}
2025-03-23 10:54:01 +01:00
/// Macro to automatically generate code to use a specific trait as an rmc protocol for calling to
/// remote objects or accepting incoming remote requests.
/// This is needed in order to be able to use this as part of an rmc server interface.
///
/// The protocol id which is needed to be specified is specified as a parameter to this attribute.
///
/// You will also need to assign each function inside the trait a method id by using the
/// [`macro@method_id`] attribute.
///
/// You can also specify to have the protocol to be non-returning by adding a second parameter to
2025-06-29 11:40:42 +02:00
/// the attribute which is just `NoReturn` e.g. `#[rmc_proto(1, NoReturn)]`
2025-03-23 10:54:01 +01:00
///
/// Example
/// ```
/// // this rmc protocol has protocol id 1
/// use macros::rmc_proto;
///
/// #[rmc_proto(1)]
/// trait ExampleProtocol{
/// // this defines an rmc method with id 1
/// #[rmc_method(1)]
/// async fn hello_world_method(&self, name: String) -> Result<String, ErrorCode>;
/// }
/// ```
#[proc_macro_attribute]
2025-06-29 11:40:42 +02:00
pub fn rmc_proto(attr: TokenStream, input: TokenStream) -> TokenStream {
let params = parse_macro_input!(attr as ProtoInputParams);
2025-03-08 00:56:44 +01:00
2025-06-29 11:40:42 +02:00
let ProtoInputParams {
2025-03-08 00:56:44 +01:00
proto_num,
2025-06-29 11:40:42 +02:00
properties,
2025-03-08 00:56:44 +01:00
} = params;
2025-06-29 11:40:42 +02:00
let no_return_data =
properties.is_some_and(|p| p.1.iter().any(|i| i.to_string() == "NoReturn"));
2025-03-08 00:56:44 +01:00
2025-06-29 11:40:42 +02:00
let input = parse_macro_input!(input as syn::ItemTrait);
2025-03-23 10:54:01 +01:00
// gigantic ass struct initializer (to summarize this gets all of the data)
2025-06-29 11:40:42 +02:00
let raw_data = RmcProtocolData {
2025-03-23 10:54:01 +01:00
has_returns: !no_return_data,
name: input.ident.clone(),
id: proto_num,
methods: input
.items
.iter()
2025-06-29 11:40:42 +02:00
.filter_map(|v| match v {
TraitItem::Fn(v) => Some(v),
_ => None,
})
.map(|func| {
let Some(attr) = func.attrs.iter().find(|a| {
a.path()
.segments
.last()
.is_some_and(|s| s.ident.to_string() == "method_id")
}) else {
panic!("every function inside of an rmc protocol must have a method id");
2025-03-08 00:56:44 +01:00
};
2025-03-23 10:54:01 +01:00
let Ok(id): Result<LitInt, _> = attr.parse_args() else {
panic!("todo: put a propper error message here");
};
2025-03-08 00:56:44 +01:00
2025-03-23 10:54:01 +01:00
let funcs = func
.sig
.inputs
.iter()
.skip(1)
.map(|f| {
let FnArg::Typed(t) = f else {
panic!("what");
};
let Pat::Ident(i) = &*t.pat else {
2025-06-29 11:40:42 +02:00
panic!(
"unable to handle non identifier patterns as parameter bindings"
);
2025-03-23 10:54:01 +01:00
};
(i.ident.clone(), t.ty.as_ref().clone())
2025-06-29 11:40:42 +02:00
})
.collect();
2025-03-23 10:54:01 +01:00
2025-06-29 11:40:42 +02:00
ProtoMethodData {
2025-03-23 10:54:01 +01:00
id,
name: func.sig.ident.clone(),
parameters: funcs,
2025-06-29 11:40:42 +02:00
ret_val: func.sig.output.clone(),
2025-03-08 00:56:44 +01:00
}
2025-06-29 11:40:42 +02:00
})
.collect(),
2025-03-23 10:54:01 +01:00
};
2025-03-08 00:56:44 +01:00
2025-06-29 11:40:42 +02:00
quote! {
#input
2025-03-23 10:54:01 +01:00
#raw_data
2025-06-29 11:40:42 +02:00
}
.into()
}
2025-03-23 10:54:01 +01:00
/// Used to specify the method id of methods when making rmc protocols.
/// See [`macro@rmc_proto`] for further details.
///
/// Note: This attribute doesn't do anything by itself and just returns the thing it was attached to
/// unchanged.
#[proc_macro_attribute]
2025-06-29 11:40:42 +02:00
pub fn method_id(_attr: TokenStream, input: TokenStream) -> TokenStream {
// this attribute doesnt do anything by itself, see `rmc_proto`
input
}
#[proc_macro_attribute]
2025-06-29 11:40:42 +02:00
pub fn rmc_struct(attr: TokenStream, input: TokenStream) -> TokenStream {
let type_data = parse_macro_input!(input as DeriveInput);
let mut ident = parse_macro_input!(attr as syn::Path);
let last_token = ident.segments.last_mut().expect("empty path?");
2025-06-29 11:40:42 +02:00
last_token.ident = Ident::new(
&("Local".to_owned() + &last_token.ident.to_string()),
last_token.span(),
);
let struct_name = &type_data.ident;
2025-06-29 11:40:42 +02:00
let out = quote! {
#type_data
impl #ident for #struct_name{
}
2025-09-21 15:59:27 +02:00
impl rnex_core::rmc::protocols::RmcCallable for #struct_name{
async fn rmc_call(&self, remote_response_connection: &rnex_core::util::SendingBufferConnection, protocol_id: u16, method_id: u32, call_id: u32, rest: Vec<u8>){
2025-03-23 10:54:01 +01:00
<Self as #ident>::rmc_call(self, remote_response_connection, protocol_id, method_id, call_id, rest).await;
}
}
};
out.into()
2025-03-08 00:56:44 +01:00
}
#[proc_macro_attribute]
2025-06-29 11:40:42 +02:00
pub fn connection(_attr: TokenStream, input: TokenStream) -> TokenStream {
2025-03-08 00:56:44 +01:00
// this attribute doesnt do anything by itself, see `rmc_struct`
input
2025-06-29 11:40:42 +02:00
}