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
|
//! 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
//!
//! ```rust,ignore
//! #[derive(Groupped, clap::Parser)]
//! #[dispatcher_clap("command_name", DispatcherName)]
//! struct MyEntry {
//! #[arg(long, short)]
//! name: String,
//! }
//! ```
//!
//! Or with explicit program name:
//!
//! ```rust,ignore
//! #[dispatcher_clap(MyProgram, "ok", CommandOk, error = CommandParseError)]
//! struct OkEntry {
//! #[arg(long, short)]
//! str: String,
//! }
//! ```
//!
//! Or with help:
//!
//! ```rust,ignore
//! #[dispatcher_clap("ok", CommandOk, error = CommandParseError, help = true)]
//! struct OkEntry {
//! #[arg(long, short)]
//! str: String,
//! }
//! ```
use proc_macro::TokenStream;
use quote::quote;
use syn::{
Ident, ItemStruct, LitBool, LitStr, Token,
parse::{Parse, ParseStream},
parse_macro_input,
};
/// Parsed key-value options after the first positional arguments
struct ClapOptions {
/// `error = ErrorStruct`
error_struct: Option<Ident>,
/// `help = true` (bool only)
help_enabled: bool,
}
impl Parse for ClapOptions {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut error_struct = None;
let mut help_enabled = false;
while !input.is_empty() {
// Parse leading comma
input.parse::<Token![,]>()?;
let key: Ident = input.parse()?;
input.parse::<Token![=]>()?;
if key == "error" {
let value: Ident = input.parse()?;
if error_struct.is_some() {
return Err(syn::Error::new(key.span(), "duplicate `error` key"));
}
error_struct = Some(value);
} else if key == "help" {
let value: LitBool = input.parse()?;
if value.value() == false {
// help = false is allowed but does nothing
help_enabled = false;
} else {
help_enabled = true;
}
} else {
return Err(syn::Error::new(
key.span(),
"unknown key, expected `error` or `help`",
));
}
}
Ok(ClapOptions {
error_struct,
help_enabled,
})
}
}
/// Input for the dispatcher_clap attribute
enum DispatcherClapInput {
/// `("cmd", Disp, ...)`
Default {
command_name: LitStr,
dispatcher_struct: Ident,
options: ClapOptions,
},
/// `(Program, "cmd", Disp, ...)`
Explicit {
group_name: Ident,
command_name: LitStr,
dispatcher_struct: Ident,
options: ClapOptions,
},
}
impl Parse for DispatcherClapInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(Ident) && input.peek2(Token![,]) && input.peek3(syn::LitStr) {
// Explicit format: Program, "cmd", Disp, ...
let group_name: Ident = input.parse()?;
input.parse::<Token![,]>()?;
let command_name: LitStr = input.parse()?;
input.parse::<Token![,]>()?;
let dispatcher_struct: Ident = input.parse()?;
let options = if input.is_empty() {
ClapOptions {
error_struct: None,
help_enabled: false,
}
} else {
input.parse::<ClapOptions>()?
};
Ok(DispatcherClapInput::Explicit {
group_name,
command_name,
dispatcher_struct,
options,
})
} else if lookahead.peek(syn::LitStr) {
// Default format: "cmd", Disp, ...
let command_name: LitStr = input.parse()?;
input.parse::<Token![,]>()?;
let dispatcher_struct: Ident = input.parse()?;
let options = if input.is_empty() {
ClapOptions {
error_struct: None,
help_enabled: false,
}
} else {
input.parse::<ClapOptions>()?
};
Ok(DispatcherClapInput::Default {
command_name,
dispatcher_struct,
options,
})
} else {
Err(lookahead.error())
}
}
}
pub fn dispatcher_clap_attr(attr: TokenStream, item: TokenStream) -> TokenStream {
let attr_input = parse_macro_input!(attr as DispatcherClapInput);
let input_struct = parse_macro_input!(item as ItemStruct);
let struct_name = &input_struct.ident;
// Determine the program name and other fields
let (command_name_str, dispatcher_struct, options, program_ident) = match &attr_input {
DispatcherClapInput::Default {
command_name,
dispatcher_struct,
options,
} => (
command_name.value(),
dispatcher_struct.clone(),
ClapOptions {
error_struct: options.error_struct.clone(),
help_enabled: options.help_enabled,
},
Ident::new("ThisProgram", proc_macro2::Span::call_site()),
),
DispatcherClapInput::Explicit {
group_name,
command_name,
dispatcher_struct,
options,
} => (
command_name.value(),
dispatcher_struct.clone(),
ClapOptions {
error_struct: options.error_struct.clone(),
help_enabled: options.help_enabled,
},
group_name.clone(),
),
};
// Generate the `begin` method body
let begin_body = if let Some(ref error_struct) = options.error_struct {
quote! {
match <#struct_name as ::clap::Parser>::try_parse_from(clap_args) {
Ok(parsed) => parsed.to_chain(),
Err(e) => {
return #error_struct::new(e.to_string()).to_render()
},
}
}
} else {
quote! {
let parsed = <#struct_name as ::clap::Parser>::try_parse_from(clap_args)
.unwrap_or_else(|e| e.exit());
parsed.to_chain()
}
};
// Generate the error pack type
let error_pack = options.error_struct.as_ref().map(|error_struct| {
quote! {
::mingling::macros::pack!(#program_ident, #error_struct = String);
}
});
// Generate the #[help] block if help = true
let help_gen = if options.help_enabled {
let dispatcher_name_str = dispatcher_struct.to_string();
let help_fn_name_str = format!("__{}_help", just_fmt::snake_case!(&dispatcher_name_str));
let help_fn_name = Ident::new(&help_fn_name_str, proc_macro2::Span::call_site());
Some(quote! {
#[allow(non_snake_case)]
#[::mingling::macros::help]
fn #help_fn_name(_prev: #struct_name) {
let mut buf = Vec::new();
<#struct_name as ::clap::CommandFactory>::command()
.write_help(&mut buf)
.unwrap();
let help_txt = String::from_utf8(buf).unwrap();
r_println!("{}", help_txt)
}
})
} else {
None
};
let expanded = quote! {
// Keep the original struct definition
#input_struct
// Generate the error wrapper type via pack!
#error_pack
// Generate the help block if enabled
#help_gen
// Generate the dispatcher struct
#[doc(hidden)]
struct #dispatcher_struct;
impl ::mingling::Dispatcher<#program_ident> for #dispatcher_struct {
fn node(&self) -> ::mingling::Node {
::mingling::macros::node!(#command_name_str)
}
fn begin(
&self,
args: Vec<String>,
) -> ::mingling::ChainProcess<#program_ident> {
// Prepend a dummy program name for clap's parse_from
let clap_args = std::iter::once(String::new())
.chain(args)
.collect::<Vec<_>>();
#begin_body
}
fn clone_dispatcher(
&self,
) -> Box<dyn ::mingling::Dispatcher<#program_ident>> {
Box::new(#dispatcher_struct)
}
}
};
expanded.into()
}
|