aboutsummaryrefslogtreecommitdiff
path: root/mingling_macros/src/dispatcher_clap.rs
blob: 58d30fc81b97f6c87d836eeecf25782b4ecbeb3b (plain) (blame)
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
//! Dispatcher Clap Attribute Macro
//!
//! This module provides the `#[dispatcher_clap(...)]` attribute macro for
//! automatically generating a `Dispatcher` implementation that uses `clap::Parser`
//! to parse command arguments into the annotated struct.
//!
//! This macro is only available when the `clap_parser` feature is enabled.
//!
//! # Syntax
//!
//! ## Two-argument form (parse failure calls `e.exit()`):
//!
//! ```rust,ignore
//! #[derive(Groupped, clap::Parser)]
//! #[dispatcher_clap("command_name", DispatcherName)]
//! struct MyEntry {
//!     #[arg(long, short)]
//!     name: String,
//! }
//! ```
//!
//! ## Three-argument form (parse failure routes to error struct):
//!
//! ```rust,ignore
//! #[derive(Groupped, clap::Parser)]
//! #[dispatcher_clap("command_name", DispatcherName, ParseError)]
//! struct MyEntry {
//!     #[arg(long, short)]
//!     name: String,
//! }
//! ```
//!
//! When three arguments are given, a pack type named `ParseError` is generated
//! that wraps the clap error message as a `String`. On parse failure, the error
//! message is routed to the renderer via `to_render()` instead of calling `e.exit()`.

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    Ident, ItemStruct, LitStr, Token,
    parse::{Parse, ParseStream},
    parse_macro_input,
};

/// Input for the dispatcher_clap attribute
///
/// Two forms:
/// - Two args: `("command_name", DispatcherStruct)`
/// - Three args: `("command_name", DispatcherStruct, ErrorStruct)`
enum DispatcherClapInput {
    /// No error type: `("cmd", DispatcherStruct)`
    Simple {
        command_name: LitStr,
        dispatcher_struct: Ident,
    },
    /// With error type: `("cmd", DispatcherStruct, ErrorStruct)`
    WithError {
        command_name: LitStr,
        dispatcher_struct: Ident,
        error_struct: Ident,
    },
}

impl Parse for DispatcherClapInput {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let command_name: LitStr = input.parse()?;
        input.parse::<Token![,]>()?;
        let dispatcher_struct: Ident = input.parse()?;

        // Check if there's a third argument (error struct)
        if input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
            let error_struct: Ident = input.parse()?;
            Ok(DispatcherClapInput::WithError {
                command_name,
                dispatcher_struct,
                error_struct,
            })
        } else {
            Ok(DispatcherClapInput::Simple {
                command_name,
                dispatcher_struct,
            })
        }
    }
}

pub fn dispatcher_clap_attr(attr: TokenStream, item: TokenStream) -> TokenStream {
    // Parse the attribute arguments
    let attr_input = parse_macro_input!(attr as DispatcherClapInput);

    // Parse the struct item to get the struct name
    let input_struct = parse_macro_input!(item as ItemStruct);
    let struct_name = &input_struct.ident;

    let expanded = match attr_input {
        DispatcherClapInput::Simple {
            command_name,
            dispatcher_struct,
        } => {
            let command_name_str = command_name.value();
            quote! {
                // Keep the original struct definition
                #input_struct

                // Generate the dispatcher struct
                #[doc(hidden)]
                pub struct #dispatcher_struct;

                impl ::mingling::Dispatcher<ThisProgram> for #dispatcher_struct {
                    fn node(&self) -> ::mingling::Node {
                        ::mingling::macros::node!(#command_name_str)
                    }

                    fn begin(
                        &self,
                        args: Vec<String>,
                    ) -> ::mingling::ChainProcess<ThisProgram> {
                        // Prepend a dummy program name for clap's parse_from
                        let clap_args = std::iter::once(String::new())
                            .chain(args)
                            .collect::<Vec<_>>();

                        // Parse using clap's Parser, exit on error
                        let parsed = <#struct_name as ::clap::Parser>::try_parse_from(clap_args)
                            .unwrap_or_else(|e| e.exit());

                        parsed.to_chain()
                    }

                    fn clone_dispatcher(
                        &self,
                    ) -> Box<dyn ::mingling::Dispatcher<ThisProgram>> {
                        Box::new(#dispatcher_struct)
                    }
                }
            }
        }
        DispatcherClapInput::WithError {
            command_name,
            dispatcher_struct,
            error_struct,
        } => {
            let command_name_str = command_name.value();
            quote! {
                // Keep the original struct definition
                #input_struct

                // Generate the error wrapper type via pack!
                ::mingling::macros::pack!(#error_struct = String);

                // Generate the dispatcher struct
                #[doc(hidden)]
                pub struct #dispatcher_struct;

                impl ::mingling::Dispatcher<ThisProgram> for #dispatcher_struct {
                    fn node(&self) -> ::mingling::Node {
                        ::mingling::macros::node!(#command_name_str)
                    }

                    fn begin(
                        &self,
                        args: Vec<String>,
                    ) -> ::mingling::ChainProcess<ThisProgram> {
                        // Prepend a dummy program name for clap's parse_from
                        let clap_args = std::iter::once(String::new())
                            .chain(args)
                            .collect::<Vec<_>>();

                        // Parse using clap's Parser, route error on failure
                        match <#struct_name as ::clap::Parser>::try_parse_from(clap_args) {
                            Ok(parsed) => parsed.to_chain(),
                            Err(e) => #error_struct::new(e.to_string()).to_render(),
                        }
                    }

                    fn clone_dispatcher(
                        &self,
                    ) -> Box<dyn ::mingling::Dispatcher<ThisProgram>> {
                        Box::new(#dispatcher_struct)
                    }
                }
            }
        }
    };

    expanded.into()
}