standout-macros 7.1.0

Proc macros for compile-time resource embedding in Standout
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! `#[handler]` proc macro for pure function handlers.
//!
//! This macro transforms pure Rust functions into Standout-compatible handlers,
//! extracting CLI arguments automatically and generating wrapper functions.
//!
//! # Example
//!
//! ```rust,ignore
//! use standout_macros::handler;
//!
//! #[handler]
//! fn list(#[flag] all: bool, #[arg] limit: Option<usize>) -> Result<Vec<Item>, Error> {
//!     storage::list(all, limit)
//! }
//!
//! // Generates:
//! // 1. Handler wrapper for dispatch
//! // pub fn list__handler(m: &ArgMatches, ctx: &CommandContext) -> Result<Vec<Item>, Error> {
//! //     let all = m.get_flag("all");
//! //     let limit = m.get_one::<usize>("limit").copied();
//! //     list(all, limit)
//! // }
//! //
//! // 2. Expected args metadata for verification
//! // pub fn list__expected_args() -> Vec<ExpectedArg> {
//! //     vec![
//! //         ExpectedArg::flag("all", "all"),
//! //         ExpectedArg::optional_arg("limit", "limit"),
//! //     ]
//! // }
//! ```
//!
//! # Verification
//!
//! The generated `__expected_args()` function can be used with
//! [`standout_dispatch::verify::verify_handler_args`] to check that a clap
//! `Command` definition matches what the handler expects:
//!
//! ```rust,ignore
//! use standout_dispatch::verify::verify_handler_args;
//!
//! let command = Command::new("list")
//!     .arg(Arg::new("all").long("all").action(ArgAction::SetTrue))
//!     .arg(Arg::new("limit").long("limit"));
//!
//! // This will return an error with helpful diagnostics if mismatched
//! verify_handler_args(&command, "list", &list__expected_args())?;
//! ```
//!
//! # Parameter Annotations
//!
//! | Annotation | Type | Extraction |
//! |------------|------|------------|
//! | `#[flag]` | `bool` | `m.get_flag("name")` |
//! | `#[flag(name = "x")]` | `bool` | `m.get_flag("x")` |
//! | `#[arg]` | `T` | `m.get_one::<T>("name").unwrap().clone()` |
//! | `#[arg]` | `Option<T>` | `m.get_one::<T>("name").cloned()` |
//! | `#[arg]` | `Vec<T>` | `m.get_many::<T>("name")...` |
//! | `#[arg(name = "x")]` | `T` | `m.get_one::<T>("x")...` |
//! | `#[ctx]` | `&CommandContext` | Pass through from wrapper |
//! | `#[matches]` | `&ArgMatches` | Pass through directly |
//!
//! # Return Type Handling
//!
//! | Return Type | Generated Wrapper Returns |
//! |-------------|---------------------------|
//! | `Result<T, E>` | `Result<T, E>` (dispatch auto-wraps via IntoHandlerResult) |
//! | `Result<(), E>` | `HandlerResult<()>` with explicit `Output::Silent` |

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    spanned::Spanned,
    Error, Expr, FnArg, ItemFn, Meta, Pat, PatType, Result, Token, Type,
};

/// Information about a parameter annotation
#[derive(Debug, Clone)]
enum ParamKind {
    /// `#[flag]` or `#[flag(name = "x")]`
    Flag { cli_name: Option<String> },
    /// `#[arg]` or `#[arg(name = "x")]`
    Arg { cli_name: Option<String> },
    /// `#[ctx]` - CommandContext reference
    Ctx,
    /// `#[matches]` - ArgMatches reference
    Matches,
    /// No annotation (not supported, will error)
    None,
}

/// Parsed parameter information
struct ParamInfo {
    /// The parameter name in Rust code
    rust_name: String,
    /// The CLI argument name (may differ from rust_name)
    cli_name: String,
    /// The parameter type
    ty: Type,
    /// What kind of parameter this is
    kind: ParamKind,
}

/// Attribute arguments for #[flag(name = "x")] or #[arg(name = "x")]
struct AttrArgs {
    name: Option<String>,
}

impl Parse for AttrArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut args = AttrArgs { name: None };

        if input.is_empty() {
            return Ok(args);
        }

        let content: Punctuated<Meta, Token![,]> = Punctuated::parse_terminated(input)?;

        for meta in content {
            if let Meta::NameValue(nv) = meta {
                if nv.path.is_ident("name") {
                    if let Expr::Lit(expr_lit) = &nv.value {
                        if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                            args.name = Some(lit_str.value());
                        } else {
                            return Err(Error::new(nv.value.span(), "expected string literal"));
                        }
                    } else {
                        return Err(Error::new(nv.value.span(), "expected string literal"));
                    }
                } else {
                    return Err(Error::new(
                        nv.path.span(),
                        "unknown attribute, expected `name`",
                    ));
                }
            }
        }

        Ok(args)
    }
}

/// Parse parameter annotations from a PatType
fn parse_param_kind(pat_type: &PatType) -> Result<ParamKind> {
    for attr in &pat_type.attrs {
        if attr.path().is_ident("flag") {
            let args: AttrArgs = if attr.meta.require_path_only().is_ok() {
                AttrArgs { name: None }
            } else {
                attr.parse_args()?
            };
            return Ok(ParamKind::Flag {
                cli_name: args.name,
            });
        }
        if attr.path().is_ident("arg") {
            let args: AttrArgs = if attr.meta.require_path_only().is_ok() {
                AttrArgs { name: None }
            } else {
                attr.parse_args()?
            };
            return Ok(ParamKind::Arg {
                cli_name: args.name,
            });
        }
        if attr.path().is_ident("ctx") {
            return Ok(ParamKind::Ctx);
        }
        if attr.path().is_ident("matches") {
            return Ok(ParamKind::Matches);
        }
    }

    Ok(ParamKind::None)
}

/// Extract the parameter name from a Pat
fn extract_param_name(pat: &Pat) -> Result<String> {
    match pat {
        Pat::Ident(ident) => Ok(ident.ident.to_string()),
        _ => Err(Error::new(
            pat.span(),
            "expected identifier pattern for parameter",
        )),
    }
}

/// Check if a type is Option<T>
fn is_option_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            return segment.ident == "Option";
        }
    }
    false
}

/// Check if a type is Vec<T>
fn is_vec_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            return segment.ident == "Vec";
        }
    }
    false
}

/// Extract the inner type from Option<T> or Vec<T>
fn extract_inner_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
                    return Some(inner);
                }
            }
        }
    }
    None
}

/// Check if a type is a reference (&T)
fn is_reference_type(ty: &Type) -> bool {
    matches!(ty, Type::Reference(_))
}

/// Check if the return type is Result<(), E> (unit result)
fn is_unit_result(fn_item: &ItemFn) -> bool {
    matches!(extract_result_ok_type(fn_item), Some(Type::Tuple(t)) if t.elems.is_empty())
}

/// Extract the Ok type from a Result<T, E> return type
fn extract_result_ok_type(fn_item: &ItemFn) -> Option<Type> {
    if let syn::ReturnType::Type(_, ty) = &fn_item.sig.output {
        if let Type::Path(type_path) = ty.as_ref() {
            if let Some(segment) = type_path.path.segments.last() {
                if segment.ident == "Result" {
                    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                        if let Some(syn::GenericArgument::Type(ok_type)) = args.args.first() {
                            return Some(ok_type.clone());
                        }
                    }
                }
            }
        }
    }
    None
}

/// Generate the expected arg expression for verification
fn generate_expected_arg(param: &ParamInfo) -> Option<TokenStream> {
    let cli_name = &param.cli_name;
    let rust_name = &param.rust_name;

    match &param.kind {
        ParamKind::Flag { .. } => Some(quote! {
            ::standout_dispatch::verify::ExpectedArg::flag(#cli_name, #rust_name)
        }),
        ParamKind::Arg { .. } => {
            let ty = &param.ty;
            if is_option_type(ty) {
                Some(quote! {
                    ::standout_dispatch::verify::ExpectedArg::optional_arg(#cli_name, #rust_name)
                })
            } else if is_vec_type(ty) {
                Some(quote! {
                    ::standout_dispatch::verify::ExpectedArg::vec_arg(#cli_name, #rust_name)
                })
            } else {
                Some(quote! {
                    ::standout_dispatch::verify::ExpectedArg::required_arg(#cli_name, #rust_name)
                })
            }
        }
        ParamKind::Ctx | ParamKind::Matches | ParamKind::None => None,
    }
}

/// Generate extraction code for a parameter
fn generate_extraction(param: &ParamInfo) -> TokenStream {
    let rust_name = format_ident!("{}", param.rust_name);
    let cli_name = &param.cli_name;
    let ty = &param.ty;

    match &param.kind {
        ParamKind::Flag { .. } => {
            quote! {
                let #rust_name: bool = __matches.get_flag(#cli_name);
            }
        }
        ParamKind::Arg { .. } => {
            if is_option_type(ty) {
                // Option<T> -> get_one::<T>().cloned()
                let inner = extract_inner_type(ty).unwrap_or(ty);
                quote! {
                    let #rust_name: #ty = __matches.get_one::<#inner>(#cli_name).cloned();
                }
            } else if is_vec_type(ty) {
                // Vec<T> -> get_many::<T>().map(|v| v.cloned().collect()).unwrap_or_default()
                let inner = extract_inner_type(ty).unwrap_or(ty);
                quote! {
                    let #rust_name: #ty = __matches
                        .get_many::<#inner>(#cli_name)
                        .map(|v| v.cloned().collect())
                        .unwrap_or_default();
                }
            } else {
                // Required T -> get_one::<T>().unwrap().clone()
                quote! {
                    let #rust_name: #ty = __matches.get_one::<#ty>(#cli_name)
                        .expect(concat!("Missing required argument '", #cli_name, "' - ensure clap definition matches handler"))
                        .clone();
                }
            }
        }
        ParamKind::Ctx | ParamKind::Matches | ParamKind::None => {
            // These don't need extraction - they're passed through
            quote! {}
        }
    }
}

/// Generate the call argument for a parameter
fn generate_call_arg(param: &ParamInfo) -> TokenStream {
    let rust_name = format_ident!("{}", param.rust_name);

    match &param.kind {
        ParamKind::Flag { .. } | ParamKind::Arg { .. } => {
            quote! { #rust_name }
        }
        ParamKind::Ctx => {
            quote! { __ctx }
        }
        ParamKind::Matches => {
            quote! { __matches }
        }
        ParamKind::None => {
            // This shouldn't happen if we validate properly
            quote! { #rust_name }
        }
    }
}

/// Extract the inner type from Output<T>
fn extract_output_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            if segment.ident == "Output" {
                if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                    if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
                        return Some(inner);
                    }
                }
            }
        }
    }
    None
}

/// Main implementation of the #[handler] macro
pub fn handler_impl(attr: TokenStream, item: TokenStream) -> Result<TokenStream> {
    // Parse the function
    let fn_item: ItemFn = syn::parse2(item)?;

    // Parse any attributes on #[handler(...)]
    // Currently unused but could support options in the future
    let _attr_args: TokenStream = attr;

    let fn_name = &fn_item.sig.ident;
    let wrapper_name = format_ident!("{}__handler", fn_name);
    let fn_vis = &fn_item.vis;

    // Analyze parameters
    let mut params: Vec<ParamInfo> = Vec::new();
    let mut has_ctx = false;
    let mut _has_matches = false;

    for fn_arg in &fn_item.sig.inputs {
        match fn_arg {
            FnArg::Typed(pat_type) => {
                let kind = parse_param_kind(pat_type)?;
                let rust_name = extract_param_name(&pat_type.pat)?;

                // Determine CLI name
                let cli_name = match &kind {
                    ParamKind::Flag { cli_name } | ParamKind::Arg { cli_name } => cli_name
                        .clone()
                        .unwrap_or_else(|| rust_name.replace('_', "-")),
                    _ => rust_name.clone(),
                };

                // Track ctx and matches usage
                if matches!(kind, ParamKind::Ctx) {
                    has_ctx = true;
                }
                if matches!(kind, ParamKind::Matches) {
                    _has_matches = true;
                }

                // Validate parameter annotations
                if matches!(kind, ParamKind::None) && !is_reference_type(&pat_type.ty) {
                    return Err(Error::new(
                        pat_type.span(),
                        "parameter must have #[flag], #[arg], #[ctx], or #[matches] annotation",
                    ));
                }

                params.push(ParamInfo {
                    rust_name,
                    cli_name,
                    ty: (*pat_type.ty).clone(),
                    kind,
                });
            }
            FnArg::Receiver(_) => {
                return Err(Error::new(
                    fn_arg.span(),
                    "#[handler] functions cannot have self parameter",
                ));
            }
        }
    }

    // Generate extraction code
    let extractions: Vec<TokenStream> = params.iter().map(generate_extraction).collect();

    // Generate call arguments
    let call_args: Vec<TokenStream> = params.iter().map(generate_call_arg).collect();

    // Generate expected args for verification
    let expected_args: Vec<TokenStream> = params.iter().filter_map(generate_expected_arg).collect();
    let expected_args_name = format_ident!("{}__expected_args", fn_name);

    // Determine wrapper signature
    let _wrapper_params = if has_ctx {
        quote! { __matches: &::clap::ArgMatches, __ctx: &::standout_dispatch::CommandContext }
    } else {
        // Even if has_matches, we still use the simple signature
        quote! { __matches: &::clap::ArgMatches }
    };

    // Get return type
    let return_type = &fn_item.sig.output;

    // Handle unit result specially - wrap in Output::Silent
    let call_and_return = if is_unit_result(&fn_item) {
        quote! {
            #fn_name(#(#call_args),*)?;
            Ok(::standout_dispatch::Output::Silent)
        }
    } else {
        quote! {
            #fn_name(#(#call_args),*)
        }
    };

    // For unit results, we need to change the return type to HandlerResult<()>
    let wrapper_return_type = if is_unit_result(&fn_item) {
        quote! { -> ::standout_dispatch::HandlerResult<()> }
    } else {
        quote! { #return_type }
    };

    // Strip attributes from the original function's parameters
    let mut clean_fn = fn_item.clone();
    for fn_arg in &mut clean_fn.sig.inputs {
        if let FnArg::Typed(pat_type) = fn_arg {
            // Remove our custom attributes
            pat_type.attrs.retain(|attr| {
                !attr.path().is_ident("flag")
                    && !attr.path().is_ident("arg")
                    && !attr.path().is_ident("ctx")
                    && !attr.path().is_ident("matches")
            });
        }
    }

    // Generate the output
    // Generate Handler struct
    let handler_struct_name = format_ident!("{}_Handler", fn_name);
    let ok_type = extract_result_ok_type(&fn_item).ok_or_else(|| {
        Error::new(
            fn_item.sig.output.span(),
            "handler must return Result<T, E>",
        )
    })?;

    // If unit result, Output is ()
    let output_type = if is_unit_result(&fn_item) {
        quote! { () }
    } else if let Some(inner) = extract_output_type(&ok_type) {
        quote! { #inner }
    } else {
        quote! { #ok_type }
    };

    Ok(quote! {
        // Original function (with annotations stripped)
        #clean_fn

        // Generated wrapper
        #fn_vis fn #wrapper_name(__matches: &::clap::ArgMatches, __ctx: &::standout_dispatch::CommandContext) #wrapper_return_type {
            #(#extractions)*
            #call_and_return
        }

        // Generated expected args for verification
        #fn_vis fn #expected_args_name() -> ::std::vec::Vec<::standout_dispatch::verify::ExpectedArg> {
            vec![#(#expected_args),*]
        }

        // Generated Handler struct integration
        #[allow(non_camel_case_types)]
        #[derive(Clone, Copy)]
        #fn_vis struct #handler_struct_name;

        impl ::standout_dispatch::Handler for #handler_struct_name {
            type Output = #output_type;

            fn handle(&mut self, matches: &::clap::ArgMatches, ctx: &::standout_dispatch::CommandContext)
                -> ::standout_dispatch::HandlerResult<Self::Output>
            {
                ::standout_dispatch::IntoHandlerResult::into_handler_result(#wrapper_name(matches, ctx))
            }

            fn expected_args(&self) -> ::std::vec::Vec<::standout_dispatch::verify::ExpectedArg> {
                #expected_args_name()
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_option_type() {
        let ty: Type = syn::parse_quote!(Option<String>);
        assert!(is_option_type(&ty));

        let ty: Type = syn::parse_quote!(String);
        assert!(!is_option_type(&ty));
    }

    #[test]
    fn test_is_vec_type() {
        let ty: Type = syn::parse_quote!(Vec<String>);
        assert!(is_vec_type(&ty));

        let ty: Type = syn::parse_quote!(String);
        assert!(!is_vec_type(&ty));
    }
}