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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
use super::{StructItem, ValueParserExpr};
use crate::util::*;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{
Error, Expr, Field, Ident, LitBool, LitChar, LitStr, Path, Type, meta::ParseNestedMeta,
parse_quote, spanned::Spanned, token,
};
/// #[conf(serde(...))] options listed on a field of Repeat kind
pub struct RepeatSerdeItem {
pub rename: Option<LitStr>,
pub aliases: Vec<LitStr>,
pub skip: bool,
pub use_value_parser: Option<Span>,
pub deserialize_with: Option<Path>,
pub try_from: Option<Type>,
span: Span,
}
impl RepeatSerdeItem {
pub fn new(meta: ParseNestedMeta<'_>) -> Result<Self, Error> {
let mut result = Self {
rename: None,
aliases: Vec::new(),
skip: false,
use_value_parser: None,
deserialize_with: None,
try_from: None,
span: meta.input.span(),
};
if meta.input.peek(token::Paren) {
meta.parse_nested_meta(|meta| {
let path = meta.path.clone();
if path.is_ident("rename") {
set_once(
&path,
&mut result.rename,
Some(parse_required_value::<LitStr>(meta)?),
)
} else if path.is_ident("alias") {
result.aliases.push(parse_required_value::<LitStr>(meta)?);
Ok(())
} else if path.is_ident("skip") {
result.skip = true;
Ok(())
} else if path.is_ident("use_value_parser") {
set_once(&path, &mut result.use_value_parser, Some(path.span()))
} else if path.is_ident("deserialize_with") {
set_once(
&path,
&mut result.deserialize_with,
Some(parse_path_from_str(meta)?),
)
} else if path.is_ident("try_from") {
set_once(
&path,
&mut result.try_from,
Some(parse_type_from_str(meta)?),
)
} else {
Err(meta.error("unrecognized conf(serde) option"))
}
})?;
}
// Validate mutual exclusivity
if let (Some(deserialize_with), Some(use_value_parser)) =
(&result.deserialize_with, &result.use_value_parser)
{
return Err(mutually_exclusive_error(
"deserialize_with",
deserialize_with,
"use_value_parser",
use_value_parser,
));
}
if let (Some(try_from), Some(use_value_parser)) =
(&result.try_from, &result.use_value_parser)
{
return Err(mutually_exclusive_error(
"try_from",
try_from,
"use_value_parser",
use_value_parser,
));
}
if let (Some(try_from), Some(deserialize_with)) =
(&result.try_from, &result.deserialize_with)
{
return Err(mutually_exclusive_error(
"try_from",
try_from,
"deserialize_with",
deserialize_with,
));
}
Ok(result)
}
}
impl GetSpan for RepeatSerdeItem {
fn get_span(&self) -> Span {
self.span
}
}
/// Proc macro annotations parsed from a field of Repeat kind
pub struct RepeatItem {
field_name: Ident,
field_type: Type, // This is needed to help with type inference in code gen
allow_hyphen_values: bool,
allow_negative_numbers: bool,
secret: Option<LitBool>,
short_switch: Option<LitChar>,
long_switch: Option<LitStr>,
aliases: Option<LitStrArray>,
env_name: Option<LitStr>,
env_aliases: Option<LitStrArray>,
value_parser: Option<Expr>,
value_parser_os: Option<Expr>,
env_delimiter: Option<LitChar>,
no_env_delimiter: Option<Span>,
serde: Option<RepeatSerdeItem>,
description: Option<String>,
is_positional: Option<Span>,
}
impl RepeatItem {
pub fn new(field: &Field, _struct_item: &StructItem) -> Result<Self, Error> {
let field_name = field
.ident
.clone()
.ok_or_else(|| Error::new(field.span(), "missing identifier"))?;
let field_type = field.ty.clone();
let Some(inner_type) = type_is_vec(&field_type)? else {
return Err(Error::new(
field.ty.span(),
"Type of a conf(repeat) field must be Vec<T>",
));
};
let allow_hyphen_values = false;
// signed numbers often start with negative signs
let allow_negative_numbers = type_is_signed_number(&inner_type);
let mut result = Self {
field_name,
field_type,
allow_hyphen_values,
allow_negative_numbers,
secret: None,
short_switch: None,
long_switch: None,
aliases: None,
env_name: None,
env_aliases: None,
value_parser: None,
value_parser_os: None,
env_delimiter: None,
no_env_delimiter: None,
serde: None,
description: None,
is_positional: None,
};
for attr in &field.attrs {
maybe_append_doc_string(&mut result.description, &attr.meta)?;
if attr.path().is_ident("conf") || attr.path().is_ident("arg") {
attr.parse_nested_meta(|meta| {
let path = meta.path.clone();
if path.is_ident("repeat") {
Ok(())
} else if path.is_ident("short") {
set_once(
&path,
&mut result.short_switch,
parse_optional_value::<LitChar>(meta)?
.or(make_short(&result.field_name, path.span())),
)
} else if path.is_ident("long") {
set_once(
&path,
&mut result.long_switch,
parse_optional_value::<LitStr>(meta)?
.or(make_long(&result.field_name, path.span())),
)
} else if path.is_ident("aliases") {
set_once(
&path,
&mut result.aliases,
Some(parse_required_value::<LitStrArray>(meta)?),
)
} else if path.is_ident("env") {
set_once(
&path,
&mut result.env_name,
parse_optional_value::<LitStr>(meta)?
.or(make_env(&result.field_name, path.span())),
)
} else if path.is_ident("env_aliases") {
set_once(
&path,
&mut result.env_aliases,
Some(parse_required_value::<LitStrArray>(meta)?),
)
} else if path.is_ident("value_parser") {
set_once(
&path,
&mut result.value_parser,
Some(parse_required_value::<Expr>(meta)?),
)
} else if path.is_ident("value_parser_os") {
set_once(
&path,
&mut result.value_parser_os,
Some(parse_required_value::<Expr>(meta)?),
)
} else if path.is_ident("env_delimiter") {
set_once(
&path,
&mut result.env_delimiter,
Some(parse_required_value::<LitChar>(meta)?),
)
} else if path.is_ident("no_env_delimiter") {
set_once(&path, &mut result.no_env_delimiter, Some(path.span()))
} else if path.is_ident("allow_hyphen_values") {
result.allow_hyphen_values = true;
Ok(())
} else if path.is_ident("allow_negative_numbers") {
result.allow_negative_numbers = true;
Ok(())
} else if path.is_ident("secret") {
set_once(
&path,
&mut result.secret,
Some(
parse_optional_value::<LitBool>(meta)?
.unwrap_or(LitBool::new(true, path.span())),
),
)
} else if path.is_ident("serde") {
set_once(&path, &mut result.serde, Some(RepeatSerdeItem::new(meta)?))
} else if path.is_ident("pos") {
set_once(&path, &mut result.is_positional, Some(path.span()))
} else {
Err(meta.error("unrecognized conf repeat option"))
}
})?;
}
}
// Validate value_parser and value_parser_os are mutually exclusive
if let (Some(value_parser), Some(value_parser_os)) =
(&result.value_parser, &result.value_parser_os)
{
return Err(mutually_exclusive_error(
"value_parser",
value_parser,
"value_parser_os",
value_parser_os,
));
}
if let (Some(no_env_delimiter), Some(env_delimiter)) =
(&result.no_env_delimiter, &result.env_delimiter)
{
return Err(mutually_exclusive_error(
"no_env_delimiter",
no_env_delimiter,
"env_delimiter",
env_delimiter,
));
}
if let Some(env_delimiter) = &result.env_delimiter {
if result.env_name.is_none() {
return Err(Error::new(
env_delimiter.span(),
"env_delimiter has no effect if an env variable is not declared",
));
}
}
if let Some(no_env_delimiter) = &result.no_env_delimiter {
if result.env_name.is_none() {
return Err(Error::new(
*no_env_delimiter,
"no_env_delimiter has no effect if an env variable is not declared",
));
}
}
// Validate that env_delimiter is ASCII when value_parser_os is used (explicitly or implicitly)
// This is required because OsStr splitting only works safely with ASCII delimiters
if let Some(ref delim) = result.env_delimiter {
if matches!(result.get_value_parser_expr(), ValueParserExpr::OsStr(_))
&& !delim.value().is_ascii()
{
return Err(Error::new(
delim.span(),
"env_delimiter must be an ASCII character when using value_parser_os \
(or with Vec<PathBuf>/Vec<OsString> types). \
OsStr uses a platform-specific encoding and only splitting by ASCII is supported.",
));
}
}
// Validate positional argument constraints
if let Some(is_positional) = &result.is_positional {
if let Some(long_switch) = &result.long_switch {
return Err(mutually_exclusive_error(
"pos",
is_positional,
"long",
long_switch,
));
}
if let Some(short_switch) = &result.short_switch {
return Err(mutually_exclusive_error(
"pos",
is_positional,
"short",
short_switch,
));
}
}
if let Some(aliases) = &result.aliases {
if result.long_switch.is_none() && !aliases.is_empty() {
return Err(Error::new(
aliases.get_span(),
"Setting aliases without setting a long-switch is an error, \
make one of the aliases the primary switch name.",
));
}
}
if let Some(env_aliases) = &result.env_aliases {
if result.env_name.is_none() && !env_aliases.is_empty() {
return Err(Error::new(
env_aliases.get_span(),
"Setting env_aliases without setting an env is an error, \
make one of the aliases the primary env.",
));
}
}
Ok(result)
}
pub fn get_field_name(&self) -> &Ident {
&self.field_name
}
pub fn get_field_type(&self) -> Type {
self.field_type.clone()
}
pub fn get_serde_name(&self) -> LitStr {
self.serde
.as_ref()
.and_then(|serde| serde.rename.clone())
.unwrap_or_else(|| LitStr::new(&self.field_name.to_string(), self.field_name.span()))
}
pub fn get_serde_aliases(&self) -> Vec<LitStr> {
self.serde
.as_ref()
.map(|serde| serde.aliases.clone())
.unwrap_or_default()
}
pub fn get_serde_type(&self) -> Type {
// Check for try_from first
if let Some(try_from_type) = self.serde.as_ref().and_then(|serde| serde.try_from.clone()) {
// For Vec<T> fields with try_from = "U", deserialize Vec<U>
// and convert each element via TryFrom
return parse_quote! { ::std::vec::Vec<#try_from_type> };
}
let use_value_parser = self
.serde
.as_ref()
.map(|serde| serde.use_value_parser.is_some())
.unwrap_or(false);
if use_value_parser {
parse_quote! { ::std::vec::Vec<::std::string::String> }
} else {
self.field_type.clone()
}
}
pub fn get_serde_try_from(&self) -> Option<Type> {
self.serde.as_ref().and_then(|serde| serde.try_from.clone())
}
pub fn get_serde_skip(&self) -> bool {
self.serde.as_ref().map(|serde| serde.skip).unwrap_or(false)
}
pub fn get_serde_deserialize_with(&self) -> Option<Path> {
self.serde
.as_ref()
.and_then(|serde| serde.deserialize_with.clone())
}
/// Returns true if this field can receive a value from serde deserialization
pub fn has_serde_source(&self) -> bool {
self.serde.is_some() && !self.get_serde_skip()
}
/// Returns true if this field has a CLI or env source (registered with clap)
pub fn has_cli_or_env_source(&self) -> bool {
self.short_switch.is_some()
|| self.long_switch.is_some()
|| self.env_name.is_some()
|| self.is_positional.is_some()
}
/// Generate a routine that pushes a ::conf::ProgramOption corresponding to
/// this field, onto a mut Vec<ProgramOption> that is in scope.
///
pub fn gen_program_option_node(&self) -> Result<Option<TokenStream>, Error> {
let id = self.field_name.to_string();
let description = quote_opt_cow(&self.description);
let short_form = quote_opt(&self.short_switch);
let long_form = quote_opt_cow(&self.long_switch);
let env_form = quote_opt_cow(&self.env_name);
let allow_hyphen_values = self.allow_hyphen_values;
let allow_negative_numbers = self.allow_negative_numbers;
let secret = quote_opt(&self.secret);
let is_positional = self.is_positional.is_some();
let has_serde_source = self.has_serde_source();
let aliases = self
.aliases
.as_ref()
.map(|x| x.quote_elements_cow())
.unwrap_or_default();
let env_aliases = self
.env_aliases
.as_ref()
.map(|x| x.quote_elements_cow())
.unwrap_or_default();
Ok(Some(quote! {
::conf::lazybuf::Node::Leaf(::conf::ProgramOption {
id: ::std::borrow::Cow::Borrowed(#id),
parse_type: ::conf::ParseType::Repeat,
description: #description,
short_form: #short_form,
long_form: #long_form,
aliases: ::std::borrow::Cow::Borrowed(&[#aliases]),
env_form: #env_form,
env_aliases: ::std::borrow::Cow::Borrowed(&[#env_aliases]),
default_help_str: None,
is_required: false,
allow_hyphen_values: #allow_hyphen_values,
allow_negative_numbers: #allow_negative_numbers,
default_if_missing: None,
secret: #secret,
is_positional: #is_positional,
has_serde_source: #has_serde_source,
})
}))
}
pub fn gen_push_subcommands(
&self,
_subcommands_ident: &Ident,
_parsed_env: &Ident,
) -> Result<TokenStream, syn::Error> {
Ok(quote! {})
}
fn get_delimiter(&self) -> TokenStream {
quote_opt(&if self.no_env_delimiter.is_some() {
None
} else {
// Default delimiter is comma for both value_parser and value_parser_os
Some(
self.env_delimiter
.clone()
.unwrap_or_else(|| LitChar::new(',', self.field_name.span())),
)
})
}
fn get_value_parser_expr(&self) -> ValueParserExpr {
// If we have an explicit OsStr parser, use it
if let Some(ref value_parser_os) = self.value_parser_os {
return ValueParserExpr::OsStr(value_parser_os.clone());
}
// If we have an explicit value parser, use it
if let Some(ref value_parser) = self.value_parser {
return ValueParserExpr::Str(value_parser.clone());
}
// Auto-detect Vec<PathBuf> and Vec<OsString> and provide default parsers
// This only happens when no explicit parser is specified
// Note: field_type is Vec<T>, so we need to extract T first
if let Ok(Some(inner_type)) = type_is_vec(&self.field_type) {
if type_is_pathbuf(&inner_type) {
return ValueParserExpr::OsStr(
parse_quote! { |s: &::std::ffi::OsStr| -> Result<::std::path::PathBuf, ::std::convert::Infallible> { Ok(s.into()) } },
);
}
if type_is_osstring(&inner_type) {
return ValueParserExpr::OsStr(
parse_quote! { |s: &::std::ffi::OsStr| -> Result<::std::ffi::OsString, ::std::convert::Infallible> { Ok(s.into()) } },
);
}
}
// Default is FromStr::from_str which takes &str
ValueParserExpr::Str(parse_quote! { std::str::FromStr::from_str })
}
/// Generate initializer code for this repeat field.
///
/// # `if_no_conf_context_val` callback
///
/// Callback invoked when conf_context doesn't find a value (when `maybe_val` is `None`).
/// For repeat fields without serde, this returns an empty vec.
/// For repeat fields with serde, this returns the document value (with appropriate conversions).
fn gen_initializer_helper(
&self,
conf_context_ident: &Ident,
if_no_conf_context_val: &dyn Fn() -> TokenStream,
) -> Result<(TokenStream, bool), syn::Error> {
let field_type = &self.field_type;
let id = self.field_name.to_string();
let delimiter = self.get_delimiter();
let value_parser_expr = self.get_value_parser_expr();
let if_no_conf_context_val = (if_no_conf_context_val)();
// Note: We can't use rust into_iter, collect, map_err because sometimes it messes with type
// inference around the value parser
//
// Note: The line `let mut result: #field_type = Default::default();`
// is expected to be default initializing a Vec.
// It can't be `#field_type::default()` because it requires turbofish syntax.
//
// If it fails because the user put another funky type there, imo this should not really be
// supported. It's more compelling to make the value_parser option easier to use
// (easier type inference) than to support user-defined containers here, and try to
// use `.collect` etc. directly into their container. The user's code can do
// .iter().collect() after our code runs if they want.
let initializer = match value_parser_expr {
ValueParserExpr::OsStr(value_parser_os) => {
// OsStr-based value parser
quote! {
{
fn __value_parser__(
__arg__: &::std::ffi::OsStr
) -> Result<<#field_type as ::conf::InnerTypeHelper>::Ty, impl ::core::fmt::Display> {
(#value_parser_os)(__arg__)
}
use ::conf::{ConfValueSource, ProgramOption, InnerError};
use ::std::vec::Vec;
use ::std::ffi::OsStr;
let (maybe_val, opt): (Option<_>, &ProgramOption)
= #conf_context_ident.get_repeat_osstring_opt(#id, #delimiter).map_err(|err| vec![err])?;
debug_assert!(
maybe_val.as_ref().map_or(true, |(vs, _)| !vs.is_default()),
"ConfContext should never return Default - the proc-macro generates default logic"
);
let (value_source, strs): (ConfValueSource<&str>, Vec<&OsStr>) = if let Some(val) = maybe_val {
val
} else {
#if_no_conf_context_val
};
#conf_context_ident.log_config_event(#id, value_source);
let mut result: #field_type = Default::default();
let mut errors = Vec::<InnerError>::new();
result.reserve(strs.len());
for val_os_str in strs {
// Note: val_os_str is already &OsStr, no conversion needed
match __value_parser__(val_os_str) {
Ok(val) => result.push(val),
Err(err) => errors.push(
InnerError::invalid_value_os(
value_source.clone(),
val_os_str,
opt,
err.to_string()
)
),
}
}
if errors.is_empty() {
Ok(result)
} else {
Err(errors)
}
}
}
}
ValueParserExpr::Str(value_parser) => {
// String-based value parser - use get_repeat_opt
quote! {
{
fn __value_parser__(
__arg__: &str
) -> Result<<#field_type as ::conf::InnerTypeHelper>::Ty, impl ::core::fmt::Display> {
(#value_parser)(__arg__)
}
use ::conf::{ConfValueSource, ProgramOption, InnerError};
use ::std::vec::Vec;
let (maybe_val, opt): (Option<_>, &ProgramOption)
= #conf_context_ident.get_repeat_opt(#id, #delimiter).map_err(|err| vec![err])?;
debug_assert!(
maybe_val.as_ref().map_or(true, |(vs, _)| !vs.is_default()),
"ConfContext should never return Default - the proc-macro generates default logic"
);
let (value_source, strs): (ConfValueSource<&str>, Vec<&str>) = if let Some(val) = maybe_val {
val
} else {
#if_no_conf_context_val
};
#conf_context_ident.log_config_event(#id, value_source);
let mut result: #field_type = Default::default();
let mut errors = Vec::<InnerError>::new();
result.reserve(strs.len());
for val_str in strs {
match __value_parser__(val_str) {
Ok(val) => result.push(val),
Err(err) => errors.push(
InnerError::invalid_value(
value_source.clone(),
val_str,
opt,
err.to_string()
)
),
}
}
if errors.is_empty() {
Ok(result)
} else {
Err(errors)
}
}
}
}
};
Ok((initializer, true))
}
// Gen initializer
//
// Create an expression that returns initialized #field_type value, or errors.
pub fn gen_initializer(
&self,
conf_context_ident: &Ident,
) -> Result<(TokenStream, bool), syn::Error> {
// If there's no CLI or env source, this repeat wasn't registered with clap,
// so we just return the default value (empty Vec)
if !self.has_cli_or_env_source() {
let field_type = &self.field_type;
return Ok((
quote! {
{
let _ = #conf_context_ident;
let result: #field_type = Default::default();
Ok(result)
}
},
false,
));
}
let id = self.field_name.to_string();
let if_no_conf_context_val = || {
quote! {
// No args/env found, return empty vec (repeat fields default to empty)
#conf_context_ident.log_config_event(#id, ::conf::ConfValueSource::Default);
return Ok(Default::default());
}
};
self.gen_initializer_helper(conf_context_ident, &if_no_conf_context_val)
}
// Gen initializer with a provided doc val
//
// This should work similar to gen_initializer, but if the conf context produces a default
// value, we should return the doc_val instead because it has higher priority than default,
// but lower than args and env.
pub fn gen_initializer_with_doc_val(
&self,
conf_context_ident: &Ident,
doc_name: &Ident,
doc_val: &Ident,
) -> Result<(TokenStream, bool), Error> {
// If there's no CLI or env source, this repeat wasn't registered with clap,
// so we just use the serde value directly
if !self.has_cli_or_env_source() {
let id = self.field_name.to_string();
let try_from = self.get_serde_try_from();
if let Some(_try_from_type) = try_from {
// Convert each element via TryFrom
let field_name_str = self.field_name.to_string();
let inner_type = type_is_vec(&self.field_type)?
.ok_or_else(|| Error::new(self.field_type.span(), "Expected Vec<T> type"))?;
return Ok((
quote! {
{
#conf_context_ident.log_config_event(
#id,
::conf::ConfValueSource::Document(#doc_name)
);
let mut __result__ = Vec::with_capacity(#doc_val.len());
for __item__ in #doc_val {
match <#inner_type as ::core::convert::TryFrom<_>>::try_from(__item__) {
Ok(__converted__) => __result__.push(__converted__),
Err(__err__) => {
return Err(vec![::conf::InnerError::serde(
#doc_name,
#field_name_str,
__err__
)]);
}
}
}
Ok(__result__)
}
},
false,
));
} else {
return Ok((
quote! {
{
#conf_context_ident.log_config_event(
#id,
::conf::ConfValueSource::Document(#doc_name)
);
Ok(#doc_val)
}
},
false,
));
}
}
let use_value_parser = self
.serde
.as_ref()
.map(|serde| serde.use_value_parser.is_some())
.unwrap_or(false);
let try_from = self.get_serde_try_from();
if let Some(_try_from_type) = try_from {
// When try_from is set, #doc_val has type Vec<try_from_type>.
// We convert each element via TryFrom to get Vec<inner_type>.
let field_name_str = self.field_name.to_string();
// Get the inner type of Vec<T>
let inner_type = type_is_vec(&self.field_type)?
.ok_or_else(|| Error::new(self.field_type.span(), "Expected Vec<T> type"))?;
let id = self.field_name.to_string();
let if_no_conf_context_val = || {
quote! {
#conf_context_ident.log_config_event(
#id,
::conf::ConfValueSource::Document(#doc_name)
);
let mut __result__ = Vec::with_capacity(#doc_val.len());
for __item__ in #doc_val {
match <#inner_type as ::core::convert::TryFrom<_>>::try_from(__item__) {
Ok(__converted__) => __result__.push(__converted__),
Err(__err__) => {
return Err(vec![::conf::InnerError::serde(
#doc_name,
#field_name_str,
__err__
)]);
}
}
}
return Ok(__result__);
}
};
self.gen_initializer_helper(conf_context_ident, &if_no_conf_context_val)
} else if use_value_parser {
// When use_value_parser is enabled and no args/env found, use document value.
// The value_parser will be run on each element from the document.
let value_parser_expr = self.get_value_parser_expr();
let if_no_conf_context_val = || match value_parser_expr {
ValueParserExpr::Str(_) => quote! {
(ConfValueSource::Document(#doc_name), #doc_val.iter().map(String::as_str).collect())
},
ValueParserExpr::OsStr(_) => quote! {
(ConfValueSource::Document(#doc_name), #doc_val.iter().map(|s| ::std::ffi::OsStr::new(s.as_str())).collect())
},
};
self.gen_initializer_helper(conf_context_ident, &if_no_conf_context_val)
} else {
// When use_value_parser is not enabled and no args/env found, return doc value directly.
let id = self.field_name.to_string();
let if_no_conf_context_val = || {
quote! {
#conf_context_ident.log_config_event(
#id,
::conf::ConfValueSource::Document(#doc_name)
);
return Ok(#doc_val);
}
};
self.gen_initializer_helper(conf_context_ident, &if_no_conf_context_val)
}
}
/// Generate debug assertions for this repeat
/// Repeats don't support default_value, so nothing to check
pub fn gen_debug_asserts(&self, _struct_ident: &Ident) -> Result<TokenStream, Error> {
Ok(quote! {})
}
}