by-macros 0.7.20

Biyard Macros
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
extern crate proc_macro;

mod action;
mod api_model;
mod api_model_struct;
mod dynamo_entity;
mod dynamo_enum;
mod enum_prop;
mod mcp_tool;
pub(crate) mod parse_queryable_fields;
mod qdrant_entity;
mod server_fn;
#[cfg(feature = "server")]
mod query_builder_functions;
mod query_display;
mod rest_error;
#[cfg(feature = "server")]
mod sql_model;
mod sub_partition;
mod write_file;

use api_model::api_model_impl;
use dynamo_entity::dynamo_entity_impl;
use dynamo_enum::dynamo_enum_impl;
use enum_prop::enum_prop_impl;
use proc_macro::TokenStream;
use query_display::query_display_impl;
use quote::{quote, ToTokens};
use rest_error::rest_error_impl;
use sub_partition::sub_partition_impl;
use syn::{parse_macro_input, Data, DataEnum, DeriveInput, Fields};

#[proc_macro_derive(QueryDisplay)]
pub fn query_display_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    query_display_impl(input)
}

#[proc_macro_attribute]
pub fn api_model(attr: TokenStream, item: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    api_model_impl(attr.into(), item.into()).into()
}

#[proc_macro_derive(EnumProp)]
pub fn enum_prop_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    enum_prop_impl(input)
}

#[proc_macro_derive(DynamoEntity, attributes(dynamo))]
pub fn dynamo_entity_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    dynamo_entity_impl(input)
}

#[proc_macro_derive(QdrantEntity, attributes(qdrant))]
pub fn qdrant_entity_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    qdrant_entity::qdrant_entity_impl(input)
}

#[proc_macro_derive(DummyDynamoEntity, attributes(dynamo))]
pub fn dummy_dynamo_entity_derive(_input: TokenStream) -> TokenStream {
    TokenStream::new()
}

#[proc_macro_derive(DummyJsonSchema)]
pub fn dummy_json_schema_derive(_input: TokenStream) -> TokenStream {
    TokenStream::new()
}

#[proc_macro_derive(DummyOperationIo)]
pub fn dummy_operation_io_derive(_input: TokenStream) -> TokenStream {
    TokenStream::new()
}

#[proc_macro_derive(SubPartition)]
pub fn sub_partition_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    sub_partition_impl(input)
}

#[proc_macro_derive(DynamoEnum, attributes(dynamo_enum))]
pub fn dynamo_enum_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    dynamo_enum_impl(input)
}

/// #[derive(RestError)]
/// #[rest_error(status = 401, code = 1000)]
#[proc_macro_derive(RestError, attributes(rest_error))]
pub fn rest_error_derive(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();
    rest_error_impl(input)
}

#[proc_macro_derive(ApiModel)]
pub fn derive_api_model(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();

    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    let Data::Enum(DataEnum { variants, .. }) = &input.data else {
        return syn::Error::new_spanned(input.ident, "ApiModel can only be derived for enums")
            .to_compile_error()
            .into();
    };

    let try_from_arms = variants.iter().map(|v| {
        let ident = &v.ident;
        let discriminant = match &v.discriminant {
            Some((_, expr)) => quote! { #expr },
            None => quote! { compile_error!("Enum variants must have explicit discriminants"); },
        };
        tracing::trace!("discriminant: {}", discriminant.to_string());
        quote! { val if val == #discriminant => Ok(#name::#ident), }
    });

    let expanded = quote! {
        impl std::convert::TryFrom<i32> for #name {
            type Error = String;

            fn try_from(value: i32) -> std::result::Result<Self, Self::Error> {
                match value {
                    #(#try_from_arms)*
                    _ => Err(format!("Invalid {}: {}", stringify!(#name), value)),
                }
            }
        }

        impl std::convert::Into<i32> for #name {
            fn into(self) -> i32 {
                self as i32
            }
        }

        #[cfg(feature = "server")]
        impl sqlx::Type<sqlx::Postgres> for #name {
            fn type_info() -> sqlx::postgres::PgTypeInfo {
                <i32 as sqlx::Type<sqlx::Postgres>>::type_info()
            }
        }

        #[cfg(feature = "server")]
        impl sqlx::Encode<'_, sqlx::Postgres> for #name {
            fn encode_by_ref(
                &self,
                buf: &mut sqlx::postgres::PgArgumentBuffer,
            ) -> std::result::Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
                let value: i32 = (*self).clone().into();
                <i32 as sqlx::Encode<sqlx::Postgres>>::encode_by_ref(&value, buf)
            }
        }

        #[cfg(feature = "server")]
        impl<'r> sqlx::Decode<'r, sqlx::Postgres> for #name {
            fn decode(
                value: sqlx::postgres::PgValueRef<'r>,
            ) -> std::result::Result<Self, sqlx::error::BoxDynError> {
                let int_value: i32 = <i32 as sqlx::Decode<sqlx::Postgres>>::decode(value)?;
                #name::try_from(int_value)
                    .map_err(|e| Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, e)).into())
            }
        }

        impl serde::Serialize for #name {
            fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_i32(self.clone() as i32)
            }
        }

        impl<'de> serde::Deserialize<'de> for #name {
            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = i32::deserialize(deserializer)?;
                Self::try_from(value)
                    .map_err(|v| serde::de::Error::custom(format!("Failed to parse ApiModel: {}", v)))
            }
        }
    };

    tracing::trace!("ApiModel expanded: {}", expanded.to_string());

    TokenStream::from(expanded)
}

#[proc_macro_derive(DioxusController)]
pub fn derive_dioxus_controller(input: TokenStream) -> TokenStream {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_file(true)
        .with_line_number(true)
        .with_thread_ids(true)
        .with_target(false)
        .try_init();

    tracing::trace!("starting derive_dioxus_controller");
    let input = parse_macro_input!(input as DeriveInput);
    let struct_name = &input.ident;

    let mut generated_methods = vec![];

    if let Data::Struct(data_struct) = input.data {
        if let Fields::Named(fields) = data_struct.fields {
            tracing::trace!("starting parsing fields");
            for field in fields.named {
                let field_name = &field.ident.unwrap();
                let field_type = field.ty.to_token_stream().to_string();
                let field_type = field_type.trim().replace(" ", "");

                tracing::trace!(
                    "field_name: {}, field_type: {}",
                    field_name.to_string(),
                    field_type
                );

                let method: proc_macro2::TokenStream = if field_type.starts_with("Signal") {
                    let t = field_type.trim_start_matches("Signal<");
                    let t: proc_macro2::TokenStream = t[..t.len() - 1].parse().unwrap();
                    quote! {
                        pub fn #field_name(&self) -> #t {
                            (self.#field_name)()
                        }
                    }
                } else if field_type.starts_with("ReadSignal") {
                    let t = field_type.trim_start_matches("ReadSignal<");
                    let t: proc_macro2::TokenStream = t[..t.len() - 1].parse().unwrap();
                    quote! {
                        pub fn #field_name(&self) -> #t {
                            (self.#field_name)()
                        }
                    }
                } else if field_type.starts_with("ReadOnlySignal") {
                    let t = field_type.trim_start_matches("ReadOnlySignal<");
                    let t: proc_macro2::TokenStream = t[..t.len() - 1].parse().unwrap();
                    quote! {
                        pub fn #field_name(&self) -> #t {
                            (self.#field_name)()
                        }
                    }
                } else if field_type.starts_with("Memo") {
                    let t = field_type.trim_start_matches("Memo<");
                    let t: proc_macro2::TokenStream = t[..t.len() - 1].parse().unwrap();
                    quote! {
                        pub fn #field_name(&self) -> #t {
                            (self.#field_name)()
                        }
                    }
                } else if field_type.starts_with("Resource<") {
                    let t = field_type.trim_start_matches("Resource<");
                    let t: proc_macro2::TokenStream = t[..t.len() - 1].parse().unwrap();

                    quote! {
                        pub fn #field_name(&self) -> std::result::Result<#t, RenderError> {
                            Ok(self.#field_name.suspend()?())
                        }
                    }
                } else if field_type.starts_with("Loader<") {
                    let t = field_type.trim_start_matches("Loader<");
                    let t: proc_macro2::TokenStream = t[..t.len() - 1].parse().unwrap();

                    quote! {
                        pub fn #field_name(&self) -> #t {
                            (self.#field_name)()
                        }
                    }
                } else {
                    continue;
                };

                tracing::trace!("method: {}", method.to_string());

                generated_methods.push(method);
            }
        }
    }

    let expanded = quote! {
        impl #struct_name {
            #(#generated_methods)*
        }
    };

    save_file(struct_name.to_string().as_str(), &expanded.to_string());

    expanded.into()
}

/// Marks a Dioxus server function handler as an MCP tool.
///
/// This macro extracts the function body into a `{name}_mcp_impl` function that can be
/// called directly from the MCP server, while keeping the original handler intact for
/// the `#[post]`/`#[get]` macro to process.
///
/// # Usage
///
/// ```rust,ignore
/// #[mcp_tool(name = "create_post", description = "Create and publish a new post.")]
/// #[post("/api/posts", user: User)]
/// pub async fn create_post_handler(team_id: Option<TeamPartition>) -> Result<CreatePostResponse> {
///     // body is extracted into create_post_handler_mcp_impl(user, team_id)
/// }
/// ```
///
/// The generated `create_post_handler_mcp_impl` has the extracted params (e.g., `user: User`)
/// as explicit arguments, so the MCP server can call it with `self.user`.
#[proc_macro_attribute]
pub fn mcp_tool(attr: TokenStream, item: TokenStream) -> TokenStream {
    mcp_tool::mcp_tool_impl(attr.into(), item.into()).into()
}

// HTTP method attribute macros — shadow `dioxus::fullstack::{get,post,...}`.
// Under `cfg(not(tauri-web))` they forward unchanged to dioxus's macro so
// server + browser-client code is generated the same way. Under
// `cfg(tauri-web)` they emit a reqwest stub that calls
// `crate::common::fullstack::server_fn::<method>` so the bundle no longer
// depends on dioxus-fullstack's RPC transport (and therefore not on
// dioxus-web/hydrate).

#[proc_macro_attribute]
pub fn get(attr: TokenStream, item: TokenStream) -> TokenStream {
    server_fn::server_fn_impl("GET", attr, item)
}

#[proc_macro_attribute]
pub fn post(attr: TokenStream, item: TokenStream) -> TokenStream {
    server_fn::server_fn_impl("POST", attr, item)
}

#[proc_macro_attribute]
pub fn put(attr: TokenStream, item: TokenStream) -> TokenStream {
    server_fn::server_fn_impl("PUT", attr, item)
}

#[proc_macro_attribute]
pub fn patch(attr: TokenStream, item: TokenStream) -> TokenStream {
    server_fn::server_fn_impl("PATCH", attr, item)
}

#[proc_macro_attribute]
pub fn delete(attr: TokenStream, item: TokenStream) -> TokenStream {
    server_fn::server_fn_impl("DELETE", attr, item)
}

pub(crate) fn save_file(st_name: &str, output: &str) {
    if option_env!("WRITE_OUTPUT").is_none() {
        return;
    }

    let dir_path = match option_env!("API_MODEL_ARTIFACT_DIR") {
        Some(dir) => dir.to_string(),
        None => {
            let current_dir = std::env::current_dir().unwrap();
            format!(
                "{}",
                current_dir
                    .join(".build/generated_api_models")
                    .to_str()
                    .unwrap()
            )
        }
    };
    use convert_case::Casing;

    let file_path = format!(
        "{}/{}.rs",
        dir_path,
        st_name.to_case(convert_case::Case::Snake)
    );

    let dir = std::path::Path::new(&dir_path);

    use std::fs;

    if !dir.exists() {
        if let Err(e) = fs::create_dir_all(dir) {
            tracing::error!("Failed to create directory: {}", e);
        }
    }

    if let Err(e) = fs::write(&file_path, output.to_string()) {
        tracing::error!("Failed to write file: {}", e);
    } else {
        tracing::info!("generated code {} into {}", st_name, file_path);
    }
}