Skip to main content

supp_macro/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::Lit;
4use syn::{Data, DeriveInput, Fields, ItemFn, Path, parse_macro_input};
5
6#[proc_macro_attribute]
7pub fn local_db_sqlx_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
8    let input = parse_macro_input!(item as ItemFn);
9    let fn_name = &input.sig.ident;
10    let block = &input.block;
11
12    let expanded = quote! {
13        #[sqlx::test(migrator = "server::db::MIGRATOR")]
14        async fn #fn_name(pool: PgPool) -> Result<(), anyhow::Error> {
15            setup().await;
16            let _guard = install_test_pool(pool.clone());
17            #block
18        Ok(())
19        }
20    };
21
22    TokenStream::from(expanded)
23}
24
25/// Runs an async test body on ONE runtime shared by the whole test binary,
26/// obtained from `crate::common::runtime()` (as [`local_db_sqlx_test`] expects
27/// `setup()`).
28///
29/// `#[tokio::test]` builds a runtime per test and drops it when the test ends.
30/// `server::db`'s production pool is a process-wide `OnceCell`, so connections
31/// opened inside the first test's runtime are still pooled after that runtime is
32/// gone, and a later acquire fails with "A Tokio 1.x context was found, but it
33/// is being shutdown" — inside whatever test happened to run next, which is why
34/// it reads as a bug in unrelated code.
35///
36/// The body also runs inside `crate::common::tenant::scoped`, which removes the
37/// tenants it provisioned however it ends.
38#[proc_macro_attribute]
39pub fn shared_runtime_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
40    let input = parse_macro_input!(item as ItemFn);
41    if !input.sig.inputs.is_empty() {
42        return syn::Error::new_spanned(&input.sig, "shared_runtime_test takes no arguments")
43            .to_compile_error()
44            .into();
45    }
46    let fn_name = &input.sig.ident;
47    let output = &input.sig.output;
48    let block = &input.block;
49    let attrs = &input.attrs;
50
51    // The return type is preserved and the value returned: erasing it would let
52    // a test that returns `Err` pass with only an unused-`Result` warning.
53    TokenStream::from(quote! {
54        #[test]
55        #(#attrs)*
56        fn #fn_name() #output {
57            crate::common::runtime().block_on(crate::common::tenant::scoped(async #block))
58        }
59    })
60}
61
62#[proc_macro_derive(Builder, attributes(builder))]
63pub fn builder_macro(input: TokenStream) -> TokenStream {
64    // Parse the input tokens into a syntax tree
65    let input = parse_macro_input!(input as DeriveInput);
66    let name = &input.ident;
67    let generics = &input.generics; // Capture generics (including lifetimes)
68    let builder_name = syn::Ident::new(&format!("{name}Builder"), name.span());
69
70    // Check for custom error_kind attribute
71    let mut error_kind = None;
72
73    // Parse attributes
74    for attr in &input.attrs {
75        if attr.path().is_ident("builder") {
76            attr.parse_nested_meta(|meta| {
77                if meta.path.is_ident("error_kind")
78                    && let Ok(Lit::Str(lit_str)) = meta.value()?.parse()
79                {
80                    error_kind = Some(lit_str.parse::<Path>().unwrap());
81                }
82                Ok(())
83            })
84            .unwrap();
85        }
86    }
87
88    // Set a default error kind if none is provided
89    let error_kind = error_kind.expect(
90        "Error kind (e.g., FinanceError) must be specified with #[builder(error_kind = \"...\")]",
91    );
92
93    // Define a custom error type based on the struct name, e.g., CommodityError for Commodity
94    let custom_error_name = syn::Ident::new(&format!("{name}Error"), name.span());
95
96    let fields = if let Data::Struct(data) = &input.data {
97        if let Fields::Named(fields) = &data.fields {
98            fields.named.iter().collect::<Vec<_>>()
99        } else {
100            panic!("Builder macro only supports structs with named fields");
101        }
102    } else {
103        panic!("Builder macro only supports structs");
104    };
105
106    // Generate builder struct fields with the same generics (including lifetimes)
107    let builder_fields = fields.iter().map(|field| {
108        let field_name = &field.ident;
109        let field_ty = &field.ty;
110        let builder_field_type = quote! { Option<#field_ty> };
111        quote! {
112            #field_name: #builder_field_type
113        }
114    });
115
116    // Generate initialization in new()
117    let builder_fields_init = fields.iter().map(|field| {
118        let field_name = &field.ident;
119        quote! {
120            #field_name: None
121        }
122    });
123
124    // Generate setter methods
125    let setters = fields.iter().map(|field| {
126        let field_name = &field.ident;
127        let field_type = &field.ty;
128
129        if is_option_type(field_type) {
130            let inner_type = get_inner_type(field_type);
131            if is_string_type(&inner_type) {
132                // For Option<String>, accept &str
133                quote! {
134                    pub fn #field_name(&mut self, value: &str) -> &mut Self {
135                        self.#field_name = Some(Some(value.to_string()));
136                        self
137                    }
138                }
139            } else {
140                // For Option<T>, accept T directly
141                quote! {
142                    pub fn #field_name(&mut self, value: #inner_type) -> &mut Self {
143                        self.#field_name = Some(Some(value));
144                        self
145                    }
146                }
147            }
148        } else if is_string_type(field_type) {
149            // For String, accept &str
150            quote! {
151                pub fn #field_name(&mut self, value: &str) -> &mut Self {
152                    self.#field_name = Some(value.to_string());
153                    self
154                }
155            }
156        } else {
157            // For non-Option<T> and non-String fields, accept T directly
158            quote! {
159                pub fn #field_name(&mut self, value: #field_type) -> &mut Self {
160                    self.#field_name = Some(value);
161                    self
162                }
163            }
164        }
165    });
166
167    // Generate code to check for missing required fields
168    let check_required_fields = fields
169        .iter()
170        .filter(|field| !is_option_type(&field.ty))
171        .map(|field| {
172            let field_name = &field.ident;
173            let field_name_str = field_name.as_ref().unwrap().to_string();
174            quote! {
175                if self.#field_name.is_none() {
176                    missing_fields.push(#field_name_str);
177                }
178            }
179        });
180
181    // Generate build_fields
182    let build_fields = fields.iter().map(|field| {
183        let field_name = &field.ident;
184        if is_option_type(&field.ty) {
185            quote! {
186                #field_name: self.#field_name.clone().unwrap_or(None)
187            }
188        } else {
189            quote! {
190                #field_name: self.#field_name.clone().unwrap()
191            }
192        }
193    });
194
195    // Extract the lifetime parameters from generics for use in the builder struct
196    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
197
198    let expanded = quote! {
199        pub struct #builder_name #impl_generics #where_clause {
200            #(#builder_fields),*
201        }
202
203        impl #impl_generics #builder_name #ty_generics #where_clause {
204            pub fn new() -> Self {
205                Self {
206                    #(#builder_fields_init),*
207                }
208            }
209
210            #(#setters)*
211
212            pub fn build(&self) -> Result<#name #ty_generics, #error_kind> {
213                let mut missing_fields = Vec::new();
214                #(#check_required_fields)*
215
216                if !missing_fields.is_empty() {
217                    return Err(#error_kind::from(#custom_error_name::Build(format!(
218                        "{} fields are missing: {}",
219                        stringify!(#name),
220                        missing_fields.join(", ")
221                    ))));
222                }
223
224                Ok(#name {
225                    #(#build_fields),*
226                })
227            }
228        }
229
230        impl #impl_generics #name #ty_generics #where_clause {
231            pub fn builder() -> #builder_name #ty_generics {
232                #builder_name::new()
233            }
234        }
235    };
236
237    TokenStream::from(expanded)
238}
239
240/// Helper function to determine if a type is an `Option<T>`
241fn is_option_type(ty: &syn::Type) -> bool {
242    matches!(ty, syn::Type::Path(syn::TypePath { path: syn::Path { segments, .. }, .. }) if segments.iter().any(|segment| segment.ident == "Option"))
243}
244
245/// Helper function to get the inner type of an `Option<T>`
246fn get_inner_type(ty: &syn::Type) -> syn::Type {
247    if let syn::Type::Path(type_path) = ty
248        && let Some(segment) = type_path.path.segments.first()
249        && segment.ident == "Option"
250        && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
251        && let Some(syn::GenericArgument::Type(inner_type)) = args.args.first()
252    {
253        return inner_type.clone();
254    }
255    ty.clone()
256}
257
258/// Helper function to check if the type is String
259fn is_string_type(ty: &syn::Type) -> bool {
260    if let syn::Type::Path(type_path) = ty
261        && let Some(segment) = type_path.path.segments.last()
262    {
263        return segment.ident == "String";
264    }
265    false
266}
267
268/// A procedural macro for generating typed Command implementations with compile-time validation.
269///
270/// This macro provides pure value-based argument passing with compile-time type safety by generating:
271/// - Typed Args structs with proper field types passed by value only
272/// - Commands that accept Args structs directly (no `HashMap` usage)
273/// - Individual typed variables available directly in command scope
274/// - Compile-time validation of argument types and required/optional fields
275/// - Zero runtime argument parsing or validation overhead
276///
277/// # Syntax
278///
279/// ```ignore
280/// command! {
281///     CommandName {
282///         #[required]
283///         arg_name: Type,
284///         #[optional]
285///         opt_name: Type,
286///     } => {
287///         // Command implementation body
288///         // Individual typed variables are available in scope
289///     }
290/// }
291/// ```
292///
293/// # Generated Code
294///
295/// The macro generates:
296/// - A `CommandNameArgs` struct with typed fields (required fields as `Type`, optional as `Option<Type>`)
297/// - A `CommandName` struct implementing `Command` trait with typed `run(args: CommandNameArgs)` method
298/// - Individual typed variables extracted from the Args struct and available in the command body
299/// - Pure compile-time type validation with no runtime overhead
300///
301/// # Examples
302///
303/// ## Simple command with no arguments
304///
305/// ```rust
306/// # use supp_macro::command;
307/// # use async_trait::async_trait;
308/// #
309/// # #[derive(Debug)]
310/// # pub enum CmdError {
311/// #     Args(String),
312/// # }
313/// #
314/// # impl std::fmt::Display for CmdError {
315/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316/// #         match self {
317/// #             CmdError::Args(msg) => write!(f, "Argument error: {}", msg),
318/// #         }
319/// #     }
320/// # }
321/// #
322/// # impl std::error::Error for CmdError {}
323/// #
324/// # #[derive(Debug)]
325/// # pub enum CmdResult {
326/// #     String(String),
327/// # }
328/// #
329/// # #[derive(Debug, Default)]
330/// # pub struct CommandArgs {}
331/// # impl CommandArgs { pub fn new() -> Self { Self::default() } }
332/// #
333/// # #[async_trait]
334/// # pub trait Command: std::fmt::Debug {
335/// #     type Args;
336/// #     async fn run(&self, args: Self::Args) -> Result<Option<CmdResult>, CmdError>;
337/// # }
338///
339/// command! {
340///     GetVersion {
341///     } => {
342///         Ok(Some(CmdResult::String("1.0.0".to_string())))
343///     }
344/// }
345///
346/// # #[tokio::main]
347/// # async fn main() {
348/// let result = GetVersion::new().run().await.unwrap();
349/// # }
350/// ```
351///
352/// ## Command with required arguments (server-compatible types)
353///
354/// ```rust
355/// # use supp_macro::command;
356/// # use async_trait::async_trait;
357/// # use uuid::Uuid;
358/// # use num_rational::Rational64;
359/// #
360/// # #[derive(Debug, Clone)]
361/// # pub enum Argument {
362/// #     String(String),
363/// #     Uuid(Uuid),
364/// #     Rational(Rational64),
365/// # }
366/// #
367/// # #[derive(Debug)]
368/// # pub enum CmdError {
369/// #     Args(String),
370/// # }
371/// #
372/// # impl std::fmt::Display for CmdError {
373/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374/// #         match self {
375/// #             CmdError::Args(msg) => write!(f, "Argument error: {}", msg),
376/// #         }
377/// #     }
378/// # }
379/// #
380/// # impl std::error::Error for CmdError {}
381/// #
382/// # #[derive(Debug)]
383/// # pub enum CmdResult {
384/// #     String(String),
385/// # }
386/// #
387/// # #[derive(Debug, Default)]
388/// # pub struct CommandArgs {
389/// #     pub symbol: Option<String>,
390/// #     pub name: Option<String>,
391/// #     pub user_id: Option<uuid::Uuid>,
392/// # }
393/// # impl CommandArgs {
394/// #     pub fn new() -> Self { Self::default() }
395/// #     pub fn symbol(mut self, v: String) -> Self { self.symbol = Some(v); self }
396/// #     pub fn name(mut self, v: String) -> Self { self.name = Some(v); self }
397/// #     pub fn user_id(mut self, v: uuid::Uuid) -> Self { self.user_id = Some(v); self }
398/// # }
399/// #
400/// # #[async_trait]
401/// # pub trait Command: std::fmt::Debug {
402/// #     type Args;
403/// #     async fn run(&self, args: Self::Args) -> Result<Option<CmdResult>, CmdError>;
404/// # }
405///
406/// // This creates a commodity in the financial system
407/// command! {
408///     CreateCommodity {
409///         #[required]
410///         symbol: String,
411///         #[required]
412///         name: String,
413///         #[required]
414///         user_id: Uuid,
415///     } => {
416///         // Individual typed variables are automatically available
417///         Ok(Some(CmdResult::String(format!(
418///             "Created commodity {} ({}) for user {}",
419///             name, symbol, user_id
420///         ))))
421///     }
422/// }
423///
424/// # #[tokio::main]
425/// # async fn main() {
426/// let result = CreateCommodity::new()
427///     .symbol("USD".to_string())
428///     .name("US Dollar".to_string())
429///     .user_id(uuid::Uuid::new_v4())
430///     .run()
431///     .await
432///     .unwrap();
433/// # }
434/// ```
435///
436/// ## Command with optional arguments
437///
438/// ```rust
439/// # use supp_macro::command;
440/// # use async_trait::async_trait;
441/// # use uuid::Uuid;
442/// #
443/// # #[derive(Debug, Clone)]
444/// # pub enum Argument {
445/// #     String(String),
446/// #     Uuid(Uuid),
447/// # }
448/// #
449/// # #[derive(Debug)]
450/// # pub enum CmdError {
451/// #     Args(String),
452/// # }
453/// #
454/// # impl std::fmt::Display for CmdError {
455/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456/// #         match self {
457/// #             CmdError::Args(msg) => write!(f, "Argument error: {}", msg),
458/// #         }
459/// #     }
460/// # }
461/// #
462/// # impl std::error::Error for CmdError {}
463/// #
464/// # #[derive(Debug)]
465/// # pub enum CmdResult {
466/// #     String(String),
467/// # }
468/// #
469/// # #[derive(Debug, Default)]
470/// # pub struct CommandArgs {
471/// #     pub user_id: Option<uuid::Uuid>,
472/// #     pub account: Option<String>,
473/// # }
474/// # impl CommandArgs {
475/// #     pub fn new() -> Self { Self::default() }
476/// #     pub fn user_id(mut self, v: uuid::Uuid) -> Self { self.user_id = Some(v); self }
477/// #     pub fn account(mut self, v: String) -> Self { self.account = Some(v); self }
478/// # }
479/// #
480/// # #[async_trait]
481/// # pub trait Command: std::fmt::Debug {
482/// #     type Args;
483/// #     async fn run(&self, args: Self::Args) -> Result<Option<CmdResult>, CmdError>;
484/// # }
485///
486/// command! {
487///     ListTransactions {
488///         #[required]
489///         user_id: Uuid,
490///         #[optional]
491///         account: String,
492///     } => {
493///         let filter = if let Some(account) = account {
494///             format!(" for account {}", account)
495///         } else {
496///             String::new()
497///         };
498///         Ok(Some(CmdResult::String(format!("Listing transactions for user {}{}", user_id, filter))))
499///     }
500/// }
501/// ```
502///
503/// ## Command with mixed required and optional arguments
504///
505/// ```rust
506/// # use supp_macro::command;
507/// # use async_trait::async_trait;
508/// #
509/// # #[derive(Debug, Clone)]
510/// # pub enum Argument {
511/// #     String(String),
512/// #     Integer(i64),
513/// #     Boolean(bool),
514/// # }
515/// #
516/// # #[derive(Debug)]
517/// # pub enum CmdError {
518/// #     Args(String),
519/// # }
520/// #
521/// # impl std::fmt::Display for CmdError {
522/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
523/// #         match self {
524/// #             CmdError::Args(msg) => write!(f, "Argument error: {}", msg),
525/// #         }
526/// #     }
527/// # }
528/// #
529/// # impl std::error::Error for CmdError {}
530/// #
531/// # #[derive(Debug)]
532/// # pub enum CmdResult {
533/// #     Success(String),
534/// # }
535/// #
536/// # impl TryFrom<Argument> for String {
537/// #     type Error = CmdError;
538/// #     fn try_from(arg: Argument) -> Result<Self, Self::Error> {
539/// #         match arg {
540/// #             Argument::String(s) => Ok(s),
541/// #             _ => Err(CmdError::Args(format!("Cannot convert {:?} to String", arg))),
542/// #         }
543/// #     }
544/// # }
545/// #
546/// # impl TryFrom<Argument> for i64 {
547/// #     type Error = CmdError;
548/// #     fn try_from(arg: Argument) -> Result<Self, Self::Error> {
549/// #         match arg {
550/// #             Argument::Integer(i) => Ok(i),
551/// #             _ => Err(CmdError::Args(format!("Cannot convert {:?} to i64", arg))),
552/// #         }
553/// #     }
554/// # }
555/// #
556/// # impl TryFrom<Argument> for bool {
557/// #     type Error = CmdError;
558/// #     fn try_from(arg: Argument) -> Result<Self, Self::Error> {
559/// #         match arg {
560/// #             Argument::Boolean(b) => Ok(b),
561/// #             _ => Err(CmdError::Args(format!("Cannot convert {:?} to bool", arg))),
562/// #         }
563/// #     }
564/// # }
565/// #
566/// # #[async_trait]
567/// # pub trait TypedCommand {
568/// #     type Args;
569/// #     async fn run_typed(&self, args: Self::Args) -> Result<Option<CmdResult>, CmdError>;
570/// # }
571/// #
572/// # #[derive(Debug, Default)]
573/// # pub struct CommandArgs {
574/// #     pub user_id: Option<i64>,
575/// #     pub username: Option<String>,
576/// #     pub email: Option<String>,
577/// #     pub is_admin: Option<bool>,
578/// # }
579/// # impl CommandArgs {
580/// #     pub fn new() -> Self { Self::default() }
581/// #     pub fn user_id(mut self, v: i64) -> Self { self.user_id = Some(v); self }
582/// #     pub fn username(mut self, v: String) -> Self { self.username = Some(v); self }
583/// #     pub fn email(mut self, v: String) -> Self { self.email = Some(v); self }
584/// #     pub fn is_admin(mut self, v: bool) -> Self { self.is_admin = Some(v); self }
585/// # }
586/// #
587/// # #[async_trait]
588/// # pub trait Command {
589/// #     type Args;
590/// #     async fn run(&self, args: Self::Args) -> Result<Option<CmdResult>, CmdError>;
591/// # }
592///
593/// command! {
594///     CreateUserCommand {
595///         #[required]
596///         user_id: i64,
597///         #[required]
598///         username: String,
599///         #[optional]
600///         email: String,
601///         #[optional]
602///         is_admin: bool,
603///     } => {
604///         let email_str = email.map_or_else(|| format!("{}@example.com", username), |s| s.to_string());
605///         let admin_status = is_admin.unwrap_or(false);
606///
607///         let message = format!(
608///             "Created user {} (ID: {}, Email: {}, Admin: {})",
609///             username, user_id, email_str, admin_status
610///         );
611///         Ok(Some(CmdResult::Success(message)))
612///     }
613/// }
614///
615/// # #[tokio::main]
616/// # async fn main() {
617/// let result = CreateUserCommand::new()
618///     .user_id(123)
619///     .username("alice".to_string())
620///     .is_admin(true)
621///     .run()
622///     .await
623///     .unwrap();
624/// # }
625/// ```
626///
627/// ## Server-compatible Command implementation
628///
629/// ```rust
630/// # use supp_macro::command;
631/// # use async_trait::async_trait;
632/// #
633/// # #[derive(Debug, Clone)]
634/// # pub enum Argument {
635/// #     String(String),
636/// #     Integer(i64),
637/// #     Boolean(bool),
638/// # }
639/// #
640/// # #[derive(Debug)]
641/// # pub enum CmdError {
642/// #     Args(String),
643/// # }
644/// #
645/// # impl std::fmt::Display for CmdError {
646/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
647/// #         match self {
648/// #             CmdError::Args(msg) => write!(f, "Argument error: {}", msg),
649/// #         }
650/// #     }
651/// # }
652/// #
653/// # impl std::error::Error for CmdError {}
654/// #
655/// # #[derive(Debug)]
656/// # pub enum CmdResult {
657/// #     Success(String),
658/// # }
659/// #
660/// # #[derive(Debug, Default)]
661/// # pub struct CommandArgs {
662/// #     pub a: Option<i64>,
663/// #     pub b: Option<i64>,
664/// # }
665/// # impl CommandArgs {
666/// #     pub fn new() -> Self { Self::default() }
667/// #     pub fn a(mut self, v: i64) -> Self { self.a = Some(v); self }
668/// #     pub fn b(mut self, v: i64) -> Self { self.b = Some(v); self }
669/// # }
670/// #
671/// # #[async_trait]
672/// # pub trait Command {
673/// #     type Args;
674/// #     async fn run(&self, args: Self::Args) -> Result<Option<CmdResult>, CmdError>;
675/// # }
676///
677/// command! {
678///     CalculateCommand {
679///         #[required]
680///         a: i64,
681///         #[required]
682///         b: i64,
683///     } => {
684///         let result = a + b;
685///         Ok(Some(CmdResult::Success(format!("{} + {} = {}", a, b, result))))
686///     }
687/// }
688///
689/// # #[tokio::main]
690/// # async fn main() {
691/// let result = CalculateCommand::new()
692///     .a(10)
693///     .b(20)
694///     .run()
695///     .await
696///     .unwrap();
697/// # }
698/// ```
699///
700/// ## Migration from Manual Commands
701///
702/// The macro makes it easy to migrate from manual Command implementations:
703///
704/// ```rust,ignore
705/// // BEFORE: Manual implementation
706/// #[derive(Debug)]
707/// pub struct GetConfig;
708///
709/// #[async_trait]
710/// impl Command for GetConfig {
711///     async fn run<'a>(&self, args: &'a HashMap<&'a str, &'a Argument>) -> Result<Option<CmdResult>, CmdError> {
712///         if let Some(Argument::String(name)) = args.get("name") {
713///             Ok(config(name).await?.map(|v| CmdResult::String(v)))
714///         } else {
715///             Err(CmdError::Args("No field name provided".to_string()))
716///         }
717///     }
718/// }
719///
720/// // AFTER: Using the macro
721/// command! {
722///     GetConfig {
723///         #[required]
724///         name: String,
725///     } => {
726///         Ok(config(name).await?.map(|v| CmdResult::String(v)))
727///     }
728/// }
729/// ```
730///
731/// # Error Handling
732///
733/// The new pure typed system provides compile-time error prevention:
734///
735/// - Missing required arguments are compile-time errors (cannot compile without them)
736/// - Invalid argument types are compile-time errors (type checking at build time)
737/// - Runtime errors only occur in the command body logic itself
738/// - No argument validation overhead at runtime
739///
740/// # Supported Argument Types
741///
742/// The macro supports any Rust type for arguments:
743/// - `String` - Text arguments
744/// - `i64`, `u64`, etc. - Integer arguments
745/// - `bool` - Boolean arguments
746/// - `Rational64` - Rational number arguments (for financial precision)
747/// - `Uuid` - UUID arguments
748/// - `Vec<u8>` - Binary data arguments
749/// - `DateTime<Utc>` - `DateTime` arguments
750/// - Custom types - Any type can be used as an argument
751/// - `Option<T>` - Automatically applied for optional arguments
752#[proc_macro]
753pub fn command(input: TokenStream) -> TokenStream {
754    let input = parse_macro_input!(input as CommandInput);
755
756    let name = &input.name;
757    let required_args = &input.required_args;
758    let optional_args = &input.optional_args;
759    let body = &input.body;
760
761    // Generate progressive runner types for all combinations of required fields
762    let runner_types = generate_progressive_runner_types(name, required_args, optional_args, body);
763
764    // Generate the main command struct
765    let command_struct = quote! {
766        #[derive(Debug)]
767        pub struct #name;
768    };
769
770    // Generate the new() method that starts the builder chain
771    let new_method = generate_new_method(name, required_args.len(), optional_args);
772
773    let expanded = quote! {
774        #command_struct
775
776        #runner_types
777
778        #new_method
779    };
780
781    TokenStream::from(expanded)
782}
783
784/// Generate all possible runner type combinations for required fields
785fn generate_progressive_runner_types(
786    command_name: &syn::Ident,
787    required_args: &[(syn::Ident, syn::Type)],
788    optional_args: &[(syn::Ident, syn::Type)],
789    body: &syn::Block,
790) -> proc_macro2::TokenStream {
791    let num_required = required_args.len();
792    let total_combinations = 1 << num_required; // 2^num_required
793
794    let mut runner_types = Vec::new();
795
796    // Generate a runner type for each possible combination of set required fields
797    for combination in 0..total_combinations {
798        let runner_type = generate_single_runner_type(
799            command_name,
800            required_args,
801            optional_args,
802            combination,
803            num_required,
804            body,
805        );
806        runner_types.push(runner_type);
807    }
808
809    quote! {
810        #(#runner_types)*
811    }
812}
813
814/// Generate a single runner type for a specific combination of set fields
815fn generate_single_runner_type(
816    command_name: &syn::Ident,
817    required_args: &[(syn::Ident, syn::Type)],
818    optional_args: &[(syn::Ident, syn::Type)],
819    combination: usize,
820    num_required: usize,
821    body: &syn::Block,
822) -> proc_macro2::TokenStream {
823    // Create binary representation for the runner type name
824    let binary_suffix = format!("{:0width$b}", combination, width = num_required.max(1));
825    let runner_name = syn::Ident::new(
826        &format!("{command_name}Runner{binary_suffix}"),
827        command_name.span(),
828    );
829
830    // Determine which required fields are set in this combination
831    let mut struct_fields = Vec::new();
832    for (i, (field_name, field_type)) in required_args.iter().enumerate() {
833        if (combination >> i) & 1 == 1 {
834            // This required field is set in this combination
835            struct_fields.push(quote! {
836                pub #field_name: #field_type
837            });
838        }
839    }
840
841    // Always include optional fields in all runner types
842    for (field_name, field_type) in optional_args {
843        struct_fields.push(quote! {
844            pub #field_name: Option<#field_type>
845        });
846    }
847
848    // Generate the struct definition
849    let struct_def = if struct_fields.is_empty() {
850        quote! {
851            #[derive(Debug)]
852            pub struct #runner_name;
853        }
854    } else {
855        quote! {
856            #[derive(Debug)]
857            pub struct #runner_name {
858                #(#struct_fields),*
859            }
860        }
861    };
862
863    // Generate transition methods for this runner type
864    let transition_methods = generate_transition_methods(
865        command_name,
866        required_args,
867        optional_args,
868        combination,
869        num_required,
870    );
871
872    // Generate run method if this is the complete state (all required fields set)
873    let complete_mask = (1 << num_required) - 1;
874    let run_method = if combination == complete_mask {
875        generate_run_method(command_name, required_args, optional_args, body)
876    } else {
877        quote! {}
878    };
879
880    quote! {
881        #struct_def
882
883        impl #runner_name {
884            #transition_methods
885            #run_method
886        }
887    }
888}
889
890/// Generate transition methods for a runner type (field setters)
891fn generate_transition_methods(
892    command_name: &syn::Ident,
893    required_args: &[(syn::Ident, syn::Type)],
894    optional_args: &[(syn::Ident, syn::Type)],
895    current_combination: usize,
896    num_required: usize,
897) -> proc_macro2::TokenStream {
898    let mut methods = Vec::new();
899
900    // Generate setter methods for required fields not yet set
901    for (i, (field_name, field_type)) in required_args.iter().enumerate() {
902        if (current_combination >> i) & 1 == 0 {
903            // This required field is not set yet, generate a setter
904            let new_combination = current_combination | (1 << i);
905            let binary_suffix =
906                format!("{:0width$b}", new_combination, width = num_required.max(1));
907            let target_runner = syn::Ident::new(
908                &format!("{command_name}Runner{binary_suffix}"),
909                command_name.span(),
910            );
911
912            let method = generate_field_setter_method(
913                required_args,
914                optional_args,
915                field_name,
916                field_type,
917                current_combination,
918                &target_runner,
919            );
920            methods.push(method);
921        }
922    }
923
924    // Generate setter methods for optional fields (available on all runner types)
925    for (field_name, field_type) in optional_args {
926        let current_runner = syn::Ident::new(
927            &format!(
928                "{}Runner{:0width$b}",
929                command_name,
930                current_combination,
931                width = num_required.max(1)
932            ),
933            command_name.span(),
934        );
935
936        let method = generate_optional_field_setter(
937            field_name,
938            field_type,
939            &current_runner,
940            required_args,
941            optional_args,
942            current_combination,
943            num_required,
944        );
945        methods.push(method);
946    }
947
948    quote! {
949        #(#methods)*
950    }
951}
952
953/// Generate a setter method for a required field
954fn generate_field_setter_method(
955    required_args: &[(syn::Ident, syn::Type)],
956    optional_args: &[(syn::Ident, syn::Type)],
957    field_name: &syn::Ident,
958    field_type: &syn::Type,
959    current_combination: usize,
960    target_runner: &syn::Ident,
961) -> proc_macro2::TokenStream {
962    // Generate field assignments for the new state
963    let mut field_assignments = Vec::new();
964
965    // Handle required fields
966    for (i, (req_field_name, _)) in required_args.iter().enumerate() {
967        if req_field_name == field_name {
968            // This is the field being set
969            field_assignments.push(quote! {
970                #req_field_name: value
971            });
972        } else if (current_combination >> i) & 1 == 1 {
973            // This field was already set, move it from self
974            field_assignments.push(quote! {
975                #req_field_name: self.#req_field_name
976            });
977        }
978        // Fields not set in either state are omitted
979    }
980
981    // Handle optional fields (always present, move from self)
982    for (opt_field_name, _) in optional_args {
983        field_assignments.push(quote! {
984            #opt_field_name: self.#opt_field_name
985        });
986    }
987
988    // Generate the constructor call
989    let constructor = if field_assignments.is_empty() {
990        quote! { #target_runner }
991    } else {
992        quote! {
993            #target_runner {
994                #(#field_assignments),*
995            }
996        }
997    };
998
999    quote! {
1000        pub fn #field_name(self, value: #field_type) -> #target_runner {
1001            #constructor
1002        }
1003    }
1004}
1005
1006/// Generate a setter method for an optional field
1007fn generate_optional_field_setter(
1008    field_name: &syn::Ident,
1009    field_type: &syn::Type,
1010    current_runner: &syn::Ident,
1011    required_args: &[(syn::Ident, syn::Type)],
1012    optional_args: &[(syn::Ident, syn::Type)],
1013    current_combination: usize,
1014    _num_required: usize,
1015) -> proc_macro2::TokenStream {
1016    // Generate field assignments (same state, but update the optional field)
1017    let mut field_assignments = Vec::new();
1018
1019    // Handle required fields (move from self if set)
1020    for (i, (req_field_name, _)) in required_args.iter().enumerate() {
1021        if (current_combination >> i) & 1 == 1 {
1022            field_assignments.push(quote! {
1023                #req_field_name: self.#req_field_name
1024            });
1025        }
1026    }
1027
1028    // Handle optional fields
1029    for (opt_field_name, _) in optional_args {
1030        if opt_field_name == field_name {
1031            // This is the field being set
1032            field_assignments.push(quote! {
1033                #opt_field_name: Some(value)
1034            });
1035        } else {
1036            // Move other optional fields from self
1037            field_assignments.push(quote! {
1038                #opt_field_name: self.#opt_field_name
1039            });
1040        }
1041    }
1042
1043    let constructor = if field_assignments.is_empty() {
1044        quote! { #current_runner }
1045    } else {
1046        quote! {
1047            #current_runner {
1048                #(#field_assignments),*
1049            }
1050        }
1051    };
1052
1053    quote! {
1054        pub fn #field_name(self, value: #field_type) -> #current_runner {
1055            #constructor
1056        }
1057    }
1058}
1059
1060/// Generate the run method for the complete runner state
1061fn generate_run_method(
1062    _command_name: &syn::Ident,
1063    required_args: &[(syn::Ident, syn::Type)],
1064    optional_args: &[(syn::Ident, syn::Type)],
1065    body: &syn::Block,
1066) -> proc_macro2::TokenStream {
1067    // Extract field values directly (no unwrap needed!)
1068    let mut variable_assignments = Vec::new();
1069
1070    // Required fields - direct field access
1071    for (field_name, _) in required_args {
1072        variable_assignments.push(quote! {
1073            let #field_name = self.#field_name;
1074        });
1075    }
1076
1077    // Optional fields - direct field access
1078    for (field_name, _) in optional_args {
1079        variable_assignments.push(quote! {
1080            let #field_name = self.#field_name;
1081        });
1082    }
1083
1084    quote! {
1085        pub async fn run(self) -> Result<Option<CmdResult>, CmdError> {
1086            // Zero runtime checks - direct field access!
1087            #(#variable_assignments)*
1088
1089            // Original command body
1090            #body
1091        }
1092    }
1093}
1094
1095/// Generate the `new()` method for the command
1096fn generate_new_method(
1097    command_name: &syn::Ident,
1098    num_required: usize,
1099    optional_args: &[(syn::Ident, syn::Type)],
1100) -> proc_macro2::TokenStream {
1101    let initial_runner = syn::Ident::new(
1102        &format!(
1103            "{}Runner{:0width$b}",
1104            command_name,
1105            0,
1106            width = num_required.max(1)
1107        ),
1108        command_name.span(),
1109    );
1110
1111    // Initial state has no required fields set, but has optional fields as None
1112    let constructor = if optional_args.is_empty() && num_required > 0 {
1113        // Unit struct (no fields at all in initial state)
1114        quote! { #initial_runner }
1115    } else {
1116        // Struct with optional fields initialized to None
1117        let optional_field_inits = optional_args.iter().map(|(field_name, _)| {
1118            quote! { #field_name: None }
1119        });
1120
1121        if optional_field_inits.len() > 0 {
1122            quote! {
1123                #initial_runner {
1124                    #(#optional_field_inits),*
1125                }
1126            }
1127        } else {
1128            quote! { #initial_runner }
1129        }
1130    };
1131
1132    quote! {
1133        impl #command_name {
1134            pub fn new() -> #initial_runner {
1135                #constructor
1136            }
1137        }
1138    }
1139}
1140
1141struct CommandInput {
1142    name: syn::Ident,
1143    required_args: Vec<(syn::Ident, syn::Type)>,
1144    optional_args: Vec<(syn::Ident, syn::Type)>,
1145    body: syn::Block,
1146}
1147
1148impl syn::parse::Parse for CommandInput {
1149    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
1150        let name: syn::Ident = input.parse()?;
1151
1152        let content;
1153        syn::braced!(content in input);
1154
1155        let mut required_args = Vec::new();
1156        let mut optional_args = Vec::new();
1157
1158        while !content.is_empty() {
1159            // Parse attributes
1160            let mut is_optional = false;
1161            let mut is_required = false;
1162
1163            while content.peek(syn::Token![#]) {
1164                content.parse::<syn::Token![#]>()?;
1165                let attr_content;
1166                syn::bracketed!(attr_content in content);
1167                let attr_name: syn::Ident = attr_content.parse()?;
1168
1169                if attr_name == "optional" {
1170                    is_optional = true;
1171                } else if attr_name == "required" {
1172                    is_required = true;
1173                } else {
1174                    return Err(syn::Error::new(
1175                        attr_name.span(),
1176                        "Unknown attribute. Use #[required] or #[optional]",
1177                    ));
1178                }
1179            }
1180
1181            // Parse the field
1182            let arg_name: syn::Ident = content.parse()?;
1183            content.parse::<syn::Token![:]>()?;
1184            let arg_type: syn::Type = content.parse()?;
1185
1186            if content.peek(syn::Token![,]) {
1187                content.parse::<syn::Token![,]>()?;
1188            }
1189
1190            // Determine if optional (default to required if no attribute specified)
1191            let is_optional_field = if is_required && is_optional {
1192                return Err(syn::Error::new(
1193                    arg_name.span(),
1194                    "Field cannot be both #[required] and #[optional]",
1195                ));
1196            } else if is_optional {
1197                true
1198            } else {
1199                false // Default to required
1200            };
1201
1202            if is_optional_field {
1203                optional_args.push((arg_name, arg_type));
1204            } else {
1205                required_args.push((arg_name, arg_type));
1206            }
1207        }
1208
1209        // The '=>' is outside the braces
1210        input.parse::<syn::Token![=>]>()?;
1211        let body: syn::Block = input.parse()?;
1212
1213        Ok(CommandInput {
1214            name,
1215            required_args,
1216            optional_args,
1217            body,
1218        })
1219    }
1220}