trying macros

This commit is contained in:
= 2024-09-09 00:25:25 +02:00
commit 88257a8f7e
5 changed files with 97 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

46
Cargo.lock generated Normal file
View File

@ -0,0 +1,46 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "medusa_macros"
version = "0.1.0"
dependencies = [
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"

11
Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "medusa_macros"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "2.0.77", features = ["full"] }
quote = "1.0.37"

6
src/handler.rs Normal file
View File

@ -0,0 +1,6 @@
pub struct Handler {
pub module: &'static str,
pub method: &'static str,
pub handle: fn(model: &str, body: &str) -> Pin<Box<dyn Future<Output = String> + Send>>,
}

33
src/lib.rs Normal file
View File

@ -0,0 +1,33 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, punctuated::Punctuated, LitStr, Token};
#[proc_macro_attribute]
pub fn handler(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args with Punctuated::<LitStr, Token![,]>::parse_terminated);
let module = &args[0].value();
let method = &args[1].value();
let input_fn = parse_macro_input!(input as syn::ItemFn);
let fn_name: syn::Ident = input_fn.sig.ident;
let inner_fn_name = syn::Ident::new(&format!("{}_handler", fn_name), fn_name.span());
let output = quote! {
pub const #fn_name: Handler = Handler {
module: #module,
method: #method,
handle: |model: &str, body: &str| -> Pin<Box<dyn Future<Output = String> + Send>> {
Box::pin(#inner_fn_name(model, body))
}
};
pub fn #inner_fn_name(model: &str, body: &str) -> impl Future<Output = String> + Send {
#fn_name(model, body)
}
};
output.into()
}