salvo_craft_macros/lib.rs
1//! [`Salvo`](https://github.com/salvo-rs/salvo) `Handler` modular craft macros.
2
3mod craft;
4mod utils;
5
6use proc_macro::TokenStream;
7use syn::{Item, parse_macro_input};
8
9/// `#[craft]` is an attribute macro that converts methods in an `impl` block into [`Salvo`'s `Handler`](https://github.com/salvo-rs/salvo) implementations.
10///
11/// ## Example
12/// ```
13/// use salvo::oapi::extract::*;
14/// use salvo::prelude::*;
15/// use salvo_craft_macros::craft;
16///
17/// #[derive(Clone)]
18/// pub struct Service {
19/// state: i64,
20/// }
21///
22/// #[craft]
23/// impl Service {
24/// fn new(state: i64) -> Self {
25/// Self { state }
26/// }
27/// /// doc line 1
28/// /// doc line 2
29/// #[salvo_craft_macros::craft(handler)]
30/// fn add1(&self, left: QueryParam<i64>, right: QueryParam<i64>) -> String {
31/// (self.state + *left + *right).to_string()
32/// }
33/// /// doc line 3
34/// /// doc line 4
35/// #[craft(handler)]
36/// pub(crate) fn add2( self: ::std::sync::Arc<Self>, left: QueryParam<i64>, right: QueryParam<i64>) -> String {
37/// (self.state + *left + *right).to_string()
38/// }
39/// /// doc line 5
40/// /// doc line 6
41/// #[craft(handler)]
42/// pub fn add3(left: QueryParam<i64>, right: QueryParam<i64>) -> String {
43/// (*left + *right).to_string()
44/// }
45/// }
46/// ```
47/// Note: `#[craft(handler)]` can be replaced with `#[craft(endpoint(...))]` for more configuration options.
48///
49/// When using `&self` as the method receiver, the containing type must implement the `Clone` trait.
50#[proc_macro_attribute]
51pub fn craft(_args: TokenStream, input: TokenStream) -> TokenStream {
52 let item = parse_macro_input!(input as Item);
53 match craft::generate(item) {
54 Ok(stream) => stream.into(),
55 Err(e) => e.to_compile_error().into(),
56 }
57}