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
use super::FieldItem;
use crate::util::*;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::{cmp::Ordering, collections::HashMap};
use syn::{Attribute, Error, Expr, Ident, LitStr, meta::ParseNestedMeta, token};
/// #[conf(serde(...))] options listed on a struct which has `#[derive(Conf)]`
pub struct StructSerdeItem {
pub allow_unknown_fields: bool,
span: Span,
}
impl StructSerdeItem {
pub fn new(meta: ParseNestedMeta<'_>) -> Result<Self, Error> {
let mut result = Self {
allow_unknown_fields: false,
span: meta.input.span(),
};
if meta.input.peek(token::Paren) {
meta.parse_nested_meta(|meta| {
let path = meta.path.clone();
if path.is_ident("allow_unknown_fields") {
result.allow_unknown_fields = true;
Ok(())
} else {
Err(meta.error("unrecognized conf(serde) option"))
}
})?;
}
Ok(result)
}
}
impl GetSpan for StructSerdeItem {
fn get_span(&self) -> Span {
self.span
}
}
/// #[conf(test(...))] options listed on a struct which has `#[derive(Conf)]`
pub struct StructTestItem {
pub should_panic: bool,
span: Span,
}
impl StructTestItem {
pub fn new(meta: ParseNestedMeta<'_>) -> Result<Self, Error> {
let mut result = Self {
should_panic: false,
span: meta.input.span(),
};
if meta.input.peek(token::Paren) {
meta.parse_nested_meta(|meta| {
let path = meta.path.clone();
if path.is_ident("should_panic") {
result.should_panic = true;
Ok(())
} else {
Err(meta.error("unrecognized conf(test) option"))
}
})?;
}
Ok(result)
}
}
impl GetSpan for StructTestItem {
fn get_span(&self) -> Span {
self.span
}
}
/// #[conf(...)] options listed on a struct which has `#[derive(Conf)]`
///
/// Also assists with code generation related to these, such as for validations
pub struct StructItem {
pub struct_ident: Ident,
pub about: Option<LitStr>,
pub name: Option<LitStr>,
/// Override the name shown in error messages. Defaults to struct_ident if not set.
pub display_name: Option<LitStr>,
pub no_help_flag: bool,
pub env_prefix: Option<LitStr>,
pub serde: Option<StructSerdeItem>,
pub test: Option<StructTestItem>,
pub one_of_fields: Vec<(Ordering, List<Ident>)>,
pub validation_predicates: Vec<Expr>,
pub doc_string: Option<String>,
pub styles: Option<Expr>,
/// Version string for `-V`/`--version` flag.
/// `Some(None)` means use CARGO_PKG_VERSION, `Some(Some(lit))` means use the literal.
pub version: Option<Option<LitStr>>,
/// Version function for `-V`/`--version` flag. Mutually exclusive with `version`.
pub version_fn: Option<Expr>,
}
impl StructItem {
/// Parse conf options out of attributes on a struct
pub fn new(struct_ident: &Ident, attrs: &[Attribute]) -> Result<Self, Error> {
let mut result = Self {
struct_ident: struct_ident.clone(),
about: None,
name: None,
display_name: None,
no_help_flag: false,
env_prefix: None,
serde: None,
test: None,
one_of_fields: Vec::default(),
validation_predicates: Vec::default(),
doc_string: None,
styles: None,
version: None,
version_fn: None,
};
for attr in attrs {
maybe_append_doc_string(&mut result.doc_string, &attr.meta)?;
if attr.path().is_ident("conf") {
attr.parse_nested_meta(|meta| {
let path = meta.path.clone();
if path.is_ident("no_help_flag") {
result.no_help_flag = true;
Ok(())
} else if path.is_ident("about") {
set_once(
&path,
&mut result.about,
Some(parse_required_value::<LitStr>(meta)?),
)
} else if path.is_ident("name") {
set_once(
&path,
&mut result.name,
Some(parse_required_value::<LitStr>(meta)?),
)
} else if path.is_ident("display_name") {
set_once(
&path,
&mut result.display_name,
Some(parse_required_value::<LitStr>(meta)?),
)
} else if path.is_ident("env_prefix") {
set_once(
&path,
&mut result.env_prefix,
Some(parse_required_value::<LitStr>(meta)?),
)
} else if path.is_ident("serde") {
set_once(&path, &mut result.serde, Some(StructSerdeItem::new(meta)?))
} else if path.is_ident("test") {
set_once(&path, &mut result.test, Some(StructTestItem::new(meta)?))
} else if path.is_ident("validation_predicate") {
result
.validation_predicates
.push(parse_required_value::<Expr>(meta)?);
Ok(())
} else if path.is_ident("one_of_fields") {
let idents: List<Ident> = meta.input.parse()?;
if idents.elements.len() < 2 {
return Err(meta.error(
"invalid to create a constraint over fewer than two fields",
));
}
result.one_of_fields.push((Ordering::Equal, idents));
Ok(())
} else if path.is_ident("at_most_one_of_fields") {
let idents: List<Ident> = meta.input.parse()?;
if idents.elements.len() < 2 {
return Err(meta.error(
"invalid to create a constraint over fewer than two fields",
));
}
result.one_of_fields.push((Ordering::Less, idents));
Ok(())
} else if path.is_ident("at_least_one_of_fields") {
let idents: List<Ident> = meta.input.parse()?;
if idents.elements.len() < 2 {
return Err(meta.error(
"invalid to create a constraint over fewer than two fields",
));
}
result.one_of_fields.push((Ordering::Greater, idents));
Ok(())
} else if path.is_ident("styles") {
set_once(
&path,
&mut result.styles,
Some(parse_required_value::<Expr>(meta)?),
)
} else if path.is_ident("version") {
set_once(
&path,
&mut result.version,
Some(if meta.input.peek(token::Eq) {
Some(parse_required_value::<LitStr>(meta)?)
} else {
None
}),
)
} else if path.is_ident("version_fn") {
set_once(
&path,
&mut result.version_fn,
Some(parse_required_value::<Expr>(meta)?),
)
} else {
Err(meta.error("unrecognized conf option"))
}
})?;
}
}
// Check mutual exclusivity
if result.version.is_some() && result.version_fn.is_some() {
return Err(Error::new(
result.struct_ident.span(),
"version and version_fn are mutually exclusive",
));
}
Ok(result)
}
/// Get the identifier of this struct
pub fn get_ident(&self) -> &Ident {
&self.struct_ident
}
/// Get the display name for this struct (used in error messages).
/// Returns the display_name if set, otherwise the struct identifier.
pub fn get_display_name(&self) -> String {
self.display_name
.as_ref()
.map(|lit_str| lit_str.value())
.unwrap_or_else(|| self.struct_ident.to_string())
}
/// Generate a conf::ParserConfig expression, based on top-level options in this struct
pub fn gen_parser_config(&self) -> Result<TokenStream, Error> {
// This default if name is not explicitly set matches what clap-derive does.
let name = self
.name
.as_ref()
.map(|lit_str| lit_str.value())
.unwrap_or_else(|| std::env::var("CARGO_PKG_NAME").ok().unwrap_or_default());
let no_help_flag = self.no_help_flag;
let about_text = self
.about
.as_ref()
.map(|lit_str| lit_str.value())
.or(self.doc_string.clone());
let about = quote_opt(&about_text);
let styles = quote_opt(&self.styles);
let version = match (&self.version, &self.version_fn) {
(Some(None), None) => quote! { Some(|| env!("CARGO_PKG_VERSION")) },
(Some(Some(lit)), None) => quote! { Some(|| #lit) },
(None, Some(expr)) => quote! { Some(#expr) },
(None, None) => quote! { None },
(Some(_), Some(_)) => unreachable!("version and version_fn are mutually exclusive"),
};
Ok(quote! {
conf::ParserConfig {
about: #about,
name: #name,
no_help_flag: #no_help_flag,
styles: #styles,
version: #version,
}
})
}
/// Generate the transform function for PROGRAM_OPTIONS.
/// Applies struct-level prefixes (currently only env_prefix).
pub fn gen_program_options_transform(&self) -> Result<TokenStream, Error> {
if let Some(env_prefix) = &self.env_prefix {
// Apply env_prefix at struct level
Ok(quote! {
|opt: &::conf::ProgramOption| {
opt.clone().apply_flatten_prefixes("", "", #env_prefix, "")
}
})
} else {
// Identity function - no transformation at the struct level
Ok(quote! {
|opt: &::conf::ProgramOption| opt.clone()
})
}
}
/// Generate tokens that apply any validations to an instance
///
/// These tokens are the body of a validation function with signature:
///
/// fn validation(
/// #instance_ident: &Self,
/// #instance_id_prefix_ident: &str
/// ) -> Result<(), Vec<conf::InnerError>>
pub fn gen_validation_routine(
&self,
instance: &Ident,
conf_context_ident: &Ident,
fields: &[FieldItem],
) -> Result<TokenStream, Error> {
let struct_ident = &self.struct_ident;
let struct_name = self.get_display_name();
let mut predicate_evaluations = Vec::<TokenStream>::new();
let mut fields_helper = FieldsHelper::new(instance, conf_context_ident, fields);
for (ordering, list) in &self.one_of_fields {
let count_expr = fields_helper.make_count_expr_for_field_list(list)?;
// Split into single options, with ids (relative to this prefix), and flattened structs.
let (id_list, flattened_list): (Vec<String>, Vec<Ident>) =
fields_helper.split_single_options_and_flattened(list)?;
// Depending on ordering parameter, a count of 0 is either okay or an error
let zero_arm = if *ordering == Ordering::Less {
quote! { Ok(()) }
} else {
let quoted_flattened_id_list = flattened_list
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>();
quote! {
Err(#conf_context_ident.too_few_arguments_error(
#struct_name,
&[#(#id_list),*],
&[#(#quoted_flattened_id_list),*]
))
}
};
// Depending on ordering parameter, a count of > 1 is either okay or an error
let more_than_one_arm = if *ordering == Ordering::Greater {
quote! { Ok(()) }
} else {
let quoted_flattened_id_and_value_source_list = flattened_list
.iter()
.map(|ident| -> Result<TokenStream, Error> {
let field_name = ident.to_string();
let get_value_source_expr =
fields_helper.make_get_value_source_expr(ident)?;
Ok(quote! {
(#field_name, #get_value_source_expr? )
})
})
.collect::<Result<Vec<_>, _>>()?;
// Note: A lambda is used here because it's allowed that get_value_source_expr can
// fail and early return with ?, but this isn't really expected to happen.
// The functions that it is calling will all be failing earlier in the process if
// they fail at all.
//
// Early returning from this block may have unexpected consequences.
quote! {
{
let flattened_ids_and_value_sources: Result<
Vec<(&'static str, Option<(&str, ::conf::ConfValueSource::<&str>)>)>,
::conf::InnerError
> =
(|| Ok(vec![#(#quoted_flattened_id_and_value_source_list),*]))();
flattened_ids_and_value_sources.and_then(|ids_and_sources| {
Err(#conf_context_ident.too_many_arguments_error(
#struct_name,
&[#(#id_list),*],
ids_and_sources
))
})
}
}
};
// Push code which evaluates the predicate, returning Ok(()) or an Inner Error.
predicate_evaluations.push(quote! {
{
let count: u32 = #count_expr;
match count {
0 => #zero_arm,
1 => Ok(()),
_ => #more_than_one_arm,
}
}
});
}
// Apply user-provided validation predicate, if any
for user_validation_predicate in self.validation_predicates.iter() {
predicate_evaluations.push(quote! {
{
fn __validation_predicate__(
#instance: & #struct_ident
) -> Result<(), impl ::core::fmt::Display>
{
#user_validation_predicate(#instance)
}
__validation_predicate__(#instance).map_err(|err|
::conf::InnerError::validation(
#struct_name,
& #conf_context_ident .get_id_prefix(),
err
)
)
}
});
}
// Collect all predicate evluations, and aggregate their errors.
Ok(if predicate_evaluations.is_empty() {
quote! {
Ok(())
}
} else {
quote! {
let errors = [#(#predicate_evaluations),*]
.into_iter()
.filter_map(|result| result.err())
.collect::<Vec<::conf::InnerError>>();
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
})
}
}
// struct which caches lookup from ident to FieldItem, and generates tokenstreams for checking if
// these fields are present in the struct instance etc. This is used in code-gen for the built-in
// validation predicates.
struct FieldsHelper<'a> {
instance: &'a Ident,
conf_context_ident: &'a Ident,
fields: &'a [FieldItem],
cache: HashMap<Ident, &'a FieldItem>,
}
impl<'a> FieldsHelper<'a> {
pub fn new(
instance: &'a Ident,
conf_context_ident: &'a Ident,
fields: &'a [FieldItem],
) -> Self {
Self {
instance,
conf_context_ident,
fields,
cache: Default::default(),
}
}
pub fn get_field(&mut self, ident: &Ident) -> Result<&'a FieldItem, Error> {
let field_item = if let Some(val) = self.cache.get(ident) {
val
} else {
let field = self
.fields
.iter()
.find(|field| field.get_field_name() == ident)
.ok_or_else(|| Error::new(ident.span(), "identifier not found in struct"))?;
self.cache.insert(ident.clone(), field);
field
};
Ok(field_item)
}
pub fn get_is_present_expr(&mut self, ident: &Ident) -> Result<TokenStream, Error> {
let field_item = self.get_field(ident)?;
let field_type = field_item.get_field_type();
let instance = &self.instance;
if let FieldItem::Parameter(item) = field_item {
if item.get_default_value().is_some() {
return Err(Error::new(
ident.span(),
"using one_of_fields constraint with a field \
that has a default_value is invalid, since it will always be present.",
));
}
};
let tok = if type_is_bool(&field_type) {
quote! { #instance.#ident }
} else if type_is_option(&field_type)?.is_some() {
quote! { #instance.#ident.is_some() }
} else if type_is_vec(&field_type)?.is_some() {
quote! { !#instance.#ident.is_empty() }
} else {
return Err(Error::new(
ident.span(),
"field must be bool, Option<T>, or Vec<T> to use with one_of_fields constraint",
));
};
Ok(tok)
}
pub fn make_count_expr_for_field_list(
&mut self,
list: &List<Ident>,
) -> Result<TokenStream, Error> {
let u32_exprs: Vec<TokenStream> = list
.elements
.iter()
.map(|ident| -> Result<TokenStream, Error> {
let bool_expr = self.get_is_present_expr(ident)?;
Ok(quote! { #bool_expr as u32 })
})
.collect::<Result<_, _>>()?;
Ok(quote! {
#(#u32_exprs)+*
})
}
pub fn split_single_options_and_flattened(
&mut self,
list: &List<Ident>,
) -> Result<(Vec<String>, Vec<Ident>), Error> {
let mut single_opts = Vec::<String>::new();
let mut groups = Vec::<Ident>::new();
for ident in &list.elements {
let field_item = self.get_field(ident)?;
if field_item.is_single_option() {
single_opts.push(ident.to_string());
} else {
groups.push(ident.clone());
}
}
Ok((single_opts, groups))
}
pub fn make_get_value_source_expr(&mut self, ident: &Ident) -> Result<TokenStream, Error> {
let field_item = self.get_field(ident)?;
match field_item {
FieldItem::Flatten(flatten_item) => {
Ok(flatten_item.any_program_options_appeared_expr(self.conf_context_ident)?)
}
_ => Err(Error::new(
ident.span(),
"field is not flattened, this is an internal error",
)),
}
}
}