conf_derive 0.4.5

Derive macro crate used with conf
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
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
use super::{SerdeKeys, SerdeStrategy, StructItem};
use crate::util::*;
use heck::{ToKebabCase, ToShoutySnakeCase, ToSnakeCase};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::fmt::Display;
use syn::{
    Error, Field, Ident, Lifetime, LitStr, Type, meta::ParseNestedMeta, parse_quote,
    spanned::Spanned, token,
};

/// #[conf(serde(...))] options listed on a field of Flatten kind
pub struct FlattenSerdeItem {
    pub rename: Option<LitStr>,
    pub aliases: Vec<LitStr>,
    pub skip: bool,
    pub flatten: bool,
    /// If flatten(prefix) is used, this is the prefix string (snake_case field name + underscore)
    pub flatten_prefix: Option<String>,
    pub try_from: Option<Type>,
    span: Span,
}

impl FlattenSerdeItem {
    pub fn new(meta: ParseNestedMeta<'_>, field_name: &Ident) -> Result<Self, Error> {
        let mut result = Self {
            rename: None,
            aliases: Vec::new(),
            skip: false,
            flatten: false,
            flatten_prefix: 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("flatten") {
                    result.flatten = true;
                    // Check for nested (prefix) or (prefix = "...")
                    if meta.input.peek(token::Paren) {
                        meta.parse_nested_meta(|nested| {
                            if nested.path.is_ident("prefix") {
                                // Check if user provided a custom prefix string
                                let prefix =
                                    if let Some(lit) = parse_optional_value::<LitStr>(nested)? {
                                        // User-specified prefix, use as-is
                                        lit.value()
                                    } else {
                                        // Generate prefix from field name: snake_case + underscore
                                        format!("{}_", field_name.to_string().to_snake_case())
                                    };
                                result.flatten_prefix = Some(prefix);
                                Ok(())
                            } else {
                                Err(nested.error("unrecognized conf(serde(flatten(...))) option"))
                            }
                        })?;
                    }
                    Ok(())
                } 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 result.try_from.is_some() && result.flatten {
            return Err(Error::new(
                result.span,
                "try_from and flatten are mutually exclusive",
            ));
        }

        Ok(result)
    }
}

impl GetSpan for FlattenSerdeItem {
    fn get_span(&self) -> Span {
        self.span
    }
}

/// Proc macro annotations parsed from a field of Flatten kind
pub struct FlattenItem {
    field_name: Ident,
    field_type: Type,
    is_optional_type: Option<Type>,
    long_prefix: Option<LitStr>,
    env_prefix: Option<LitStr>,
    description_prefix: Option<String>,
    skip_short: Option<LitCharArray>,
    serde: Option<FlattenSerdeItem>,
}

fn make_long_prefix(ident: &impl Display, span: Span) -> Option<LitStr> {
    let formatted = format!("{}-", ident.to_string().to_kebab_case());
    Some(LitStr::new(&formatted, span))
}

fn make_env_prefix(ident: &impl Display, span: Span) -> Option<LitStr> {
    let formatted = format!("{}_", ident.to_string().to_shouty_snake_case());
    Some(LitStr::new(&formatted, span))
}

impl FlattenItem {
    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 is_optional_type = type_is_option(&field.ty)?;

        let mut result = Self {
            field_name,
            field_type,
            is_optional_type,
            long_prefix: None,
            env_prefix: None,
            description_prefix: None,
            skip_short: None,
            serde: None,
        };

        // These two variables are used to set description_prefix at the end.
        let mut doc_string: Option<String> = None;
        // If help_prefix is set, this is Some
        // If help_prefix sets an explicit value, this is Some(Some(...))
        let mut help_prefix: Option<Option<LitStr>> = None;

        for attr in &field.attrs {
            maybe_append_doc_string(&mut doc_string, &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("flatten") {
                        Ok(())
                    } else if path.is_ident("long_prefix") {
                        set_once(
                            &path,
                            &mut result.long_prefix,
                            parse_optional_value::<LitStr>(meta)?
                                .or(make_long_prefix(&result.field_name, path.span())),
                        )
                    } else if path.is_ident("env_prefix") {
                        set_once(
                            &path,
                            &mut result.env_prefix,
                            parse_optional_value::<LitStr>(meta)?
                                .or(make_env_prefix(&result.field_name, path.span())),
                        )
                    } else if path.is_ident("help_prefix") {
                        set_once(
                            &path,
                            &mut help_prefix,
                            Some(parse_optional_value::<LitStr>(meta)?),
                        )
                    } else if path.is_ident("prefix") {
                        let (long_prefix, env_prefix) = match parse_optional_value::<LitStr>(meta)?
                        {
                            Some(prefix) => (
                                make_long_prefix(&prefix.value(), path.span()),
                                make_env_prefix(&prefix.value(), path.span()),
                            ),
                            None => (
                                make_long_prefix(&result.field_name, path.span()),
                                make_env_prefix(&result.field_name, path.span()),
                            ),
                        };
                        set_once(&path, &mut result.long_prefix, long_prefix)?;
                        set_once(&path, &mut result.env_prefix, env_prefix)?;
                        Ok(())
                    } else if path.is_ident("skip_short") {
                        set_once(
                            &path,
                            &mut result.skip_short,
                            Some(parse_required_value::<LitCharArray>(meta)?),
                        )
                    } else if path.is_ident("serde") {
                        set_once(
                            &path,
                            &mut result.serde,
                            Some(FlattenSerdeItem::new(meta, &result.field_name)?),
                        )
                    } else {
                        Err(meta.error("unrecognized conf flatten option"))
                    }
                })?;
            }
        }

        // If help prefix was not requested, then doc_string should be ignored. If help_prefix was
        // explicitly assigned, then doc_string is shadowed. unwrap_or_default is used to
        // flatten the two levels of Option.
        result.description_prefix = help_prefix
            .map(|inner| inner.as_ref().map(LitStr::value).or(doc_string))
            .unwrap_or_default();

        Ok(result)
    }

    pub fn get_field_name(&self) -> &Ident {
        &self.field_name
    }

    fn get_id_prefix(&self) -> String {
        self.field_name.to_string() + "."
    }

    pub fn get_field_type(&self) -> Type {
        self.field_type.clone()
    }

    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()))
    }

    fn get_serde_aliases(&self) -> Vec<LitStr> {
        self.serde
            .as_ref()
            .map(|serde| serde.aliases.clone())
            .unwrap_or_default()
    }

    pub fn get_serde_skip(&self) -> bool {
        self.serde.as_ref().map(|serde| serde.skip).unwrap_or(false)
    }

    fn get_serde_try_from(&self) -> Option<Type> {
        self.serde.as_ref().and_then(|serde| serde.try_from.clone())
    }

    fn get_serde_flatten_prefix(&self) -> Option<&str> {
        self.serde
            .as_ref()
            .and_then(|serde| serde.flatten_prefix.as_deref())
    }

    /// Generate a Node::Branch for this flatten field.
    /// This creates a branch that references the flattened type's PROGRAM_OPTIONS
    /// with a composed transform function that applies flatten prefixes (id, long, env, description)
    /// and handles skip_short. For Option<T> flattens, also makes all options optional.
    pub fn gen_program_option_node(&self) -> Result<Option<TokenStream>, Error> {
        let inner_type = self.is_optional_type.as_ref().unwrap_or(&self.field_type);
        let id_prefix = self.get_id_prefix();
        let long_prefix = self
            .long_prefix
            .as_ref()
            .map(LitStr::value)
            .unwrap_or_default();
        let env_prefix = self
            .env_prefix
            .as_ref()
            .map(LitStr::value)
            .unwrap_or_default();
        let description_prefix = self.description_prefix.as_deref().unwrap_or_default();

        // Generate skip_short code
        let skip_short_code = if let Some(skip_short) = self.skip_short.as_ref() {
            let chars = skip_short.elements.iter();
            quote! {
                #(
                    if opt.short_form == Some(#chars) {
                        opt.short_form = None;
                    }
                )*
            }
        } else {
            quote! {}
        };

        // For Option<T> flattens, also make options optional
        let maybe_make_optional = if self.is_optional_type.is_some() {
            quote! { .make_optional() }
        } else {
            quote! {}
        };

        // Generate the composed transform function
        let transform_fn = quote! {
            |opt: &::conf::ProgramOption| {
                // First apply the inner type's transform
                let mut opt = (<#inner_type as ::conf::Conf>::PROGRAM_OPTIONS.transform)(opt);
                // Then apply flatten prefixes
                opt = opt.apply_flatten_prefixes(#id_prefix, #long_prefix, #env_prefix, #description_prefix)
                         #maybe_make_optional;
                // Apply skip_short
                #skip_short_code
                opt
            }
        };

        Ok(Some(quote! {
            ::conf::lazybuf::Node::Branch(::conf::lazybuf::LazyBuf {
                buffer: <#inner_type as ::conf::Conf>::PROGRAM_OPTIONS.buffer,
                transform: #transform_fn,
            })
        }))
    }

    // Flatten fields forward subcommands from the flattened type.
    // For flatten-optional, we don't support subcommands because `any_program_options_appeared`
    // doesn't yet handle subcommand selection as a trigger for the optional group.
    pub fn gen_push_subcommands(
        &self,
        subcommands_ident: &Ident,
        parsed_env_ident: &Ident,
    ) -> Result<TokenStream, syn::Error> {
        let inner_type: &Type = self.is_optional_type.as_ref().unwrap_or(&self.field_type);

        if self.is_optional_type.is_some() {
            // For flatten-optional, we don't support subcommands yet
            let field_name = self.field_name.to_string();
            let panic_message = format!(
                "Subcommands in flatten-optional field '{}' are not supported, see github issue #23",
                field_name
            );

            Ok(quote! {
                if !<#inner_type as ::conf::Conf>::get_subcommands(#parsed_env_ident)?.is_empty() {
                    panic!(#panic_message);
                }
            })
        } else {
            // For non-optional flatten, forward subcommands from the flattened type
            Ok(quote! {
                #subcommands_ident.extend(<#inner_type as ::conf::Conf>::get_subcommands(#parsed_env_ident)?);
            })
        }
    }

    // Body of a function taking a &ConfContext returning
    // Result<#field_type, Vec<::conf::InnerError>>
    //
    // Arguments:
    // * conf_context_ident is the identifier of a &ConfContext variable in scope
    pub fn gen_initializer(
        &self,
        conf_context_ident: &Ident,
    ) -> Result<(TokenStream, bool), syn::Error> {
        let field_type = &self.field_type;

        let id_prefix = self.get_id_prefix();

        let initializer = if let Some(inner_type) = self.is_optional_type.as_ref() {
            // This is flatten-optional
            quote! {
              let option_appeared_result =
                <#inner_type as ::conf::Conf>::any_program_options_appeared(
                  &#conf_context_ident.for_flattened(#id_prefix)
                ).map_err(|err| vec![err])?;
              Ok(if let Some(option_appeared) = option_appeared_result {
                let #conf_context_ident = #conf_context_ident.for_flattened_optional(
                  #id_prefix,
                  <#inner_type as ::conf::Conf>::get_name(),
                  option_appeared
                );
                Some(<#inner_type as ::conf::Conf>::from_conf_context(#conf_context_ident)?)
              } else {
                None
              })
            }
        } else {
            // Non-optional flatten
            quote! {
              let #conf_context_ident = #conf_context_ident.for_flattened(#id_prefix);
              <#field_type as ::conf::Conf>::from_conf_context(#conf_context_ident)
            }
        };
        Ok((initializer, true))
    }

    // Returns an expression which calls any_program_options_appeared with given conf context.
    // This is used to get errors for one_of constraint failures.
    //
    // Arguments:
    // * conf_context_ident is the identifier of a ConfContext variable that is in scope that we
    //   won't consume.
    pub fn any_program_options_appeared_expr(
        &self,
        conf_context_ident: &Ident,
    ) -> Result<TokenStream, syn::Error> {
        let field_type = &self.field_type;
        let id_prefix = self.get_id_prefix();

        let inner_type = self.is_optional_type.as_ref().unwrap_or(field_type);

        Ok(quote! {
          <#inner_type as ::conf::Conf>::any_program_options_appeared(
            & #conf_context_ident .for_flattened(#id_prefix)
          )
        })
    }

    // This is used by ConfSerde
    //
    // When walking a map access, we match on the key, and if we get the key for this field,
    // try to deserialize using DeserializeSeed.
    //
    // We have to use DeserializeSeed with the inner-type if this is flatten-optional, because
    // DeserializeSeed isn't implemented for type on Option<S>.
    //
    // We don't use the "any program options appeared" stuff here because, the key for the flattened
    // structure appeared, so that turns the group on. If that key doesn't appear when we do the
    // serde walk, then later we will try to initialize the group normally.
    //
    // Arguments:
    // * ct: context lifetime
    // * ctxt: identifier of a &ConfSerdeContext in scope
    // * nvp: identifier of a NextValueProducer in scope
    // * nvp_type: identifier of the NextValueProducer type in this scope
    // * errors_ident: identifier of a mut Vec<InnerError> errors buffer to which we can push
    pub fn gen_serde_strategy(
        &self,
        ct: &Lifetime,
        ctxt: &Ident,
        nvp: &Ident,
        nvp_type: &Ident,
        errors_ident: &Ident,
    ) -> Result<SerdeStrategy, Error> {
        let field_name = &self.field_name;
        let field_name_str = field_name.to_string();
        let field_type = &self.field_type;
        let serde_name_str = self.get_serde_name();
        let serde_aliases = self.get_serde_aliases();
        let id_prefix = self.get_id_prefix();

        // It's necessary to do special handling for optional flattened structs here,
        // because ConfSerde is only implemented on the inner one.
        //
        // We also don't *have* to do any of the "any program option appeared" stuff here,
        // because we only reach this line if serde provided a value for this struct,
        // and that should mean that the optional group is enabled, since serde mentioned it.
        //
        // Note: We may want to consider an attribute that changes this behavior, so
        // that if the group is not mentioned in args or env then it gets skipped even if
        // serde has some values.
        //
        // As it stands, if serde doesn't mention it, then the `Conf::any_program_option_appeared`
        // stuff runs in the deserializer_finalizer routine when we call Conf::from_conf_context
        // And if serde does mention it, then we have to try to deserialize regardless of what
        // `Conf::any_program_option_appeared` says.
        let inner_type = self.is_optional_type.as_ref().unwrap_or(field_type);

        let val_expr = if self.is_optional_type.is_some() {
            quote! { Some(__val__) }
        } else {
            quote! { __val__ }
        };

        if self.serde.as_ref().map(|s| s.flatten).unwrap_or(false) {
            // For the flatten case, we are going to use the state machine corresponding
            // to the thing we are flattening

            // Key matching: check prefix and then inner wants_key on stripped key
            let key = Ident::new("key__", Span::call_site());
            let keys_expr: TokenStream = quote! {
                #key if #field_name.wants_key(#key)
            };

            let match_expr: TokenStream = quote! {
                {
                    #field_name = #field_name.next(#key, #nvp);
                },
            };

            let state_machine_type: Type;
            let state_machine_init: TokenStream;

            // Build the state machine type and init, applying wrappers as needed
            // Start with the base inner type's ISM
            let base_type: Type = parse_quote! { <#inner_type as ::conf::ConfSerde>::ISM::<#ct> };
            let base_init: TokenStream = quote! { #ctxt.for_flattened(#id_prefix).into() };

            // Apply PrefixStrippingStateMachine wrapper if needed
            let (type_after_prefix, init_after_prefix) =
                if let Some(prefix) = self.get_serde_flatten_prefix() {
                    let wrapped_type: Type = parse_quote! {
                        ::conf::PrefixStrippingStateMachine<'static, #base_type>
                    };
                    let wrapped_init = quote! {
                        ::conf::PrefixStrippingStateMachine::new(#prefix, #base_init)
                    };
                    (wrapped_type, wrapped_init)
                } else {
                    (base_type, base_init)
                };

            // Apply OptionalStateMachine wrapper if this is a flatten-optional field
            if self.is_optional_type.is_some() {
                state_machine_type = parse_quote! {
                    ::conf::OptionalStateMachine<#type_after_prefix>
                };
                state_machine_init = quote! {
                    ::conf::OptionalStateMachine::new(#init_after_prefix)
                };
            } else {
                state_machine_type = type_after_prefix;
                state_machine_init = init_after_prefix;
            }

            Ok(SerdeStrategy {
                state_machine_type: Some(state_machine_type),
                state_machine_init: Some(state_machine_init),
                match_expr,
                serde_keys: SerdeKeys::Expr(keys_expr),
            })
        } else if let Some(try_from_type) = self.get_serde_try_from() {
            // When try_from is set, deserialize the try_from type using ConfSerdeSeed
            // (so CLI/env shadowing works), then convert to the target type via TryFrom.
            // The try_from type must implement ConfSerde.
            let match_expr = quote! {
              {
                if #field_name.is_some() {
                  #errors_ident.push(
                    InnerError::serde(
                      #ctxt.document_name,
                      #field_name_str,
                      #nvp_type::Error::duplicate_field(#serde_name_str)
                    )
                  );
                } else {
                  let __seed__ = ConfSerdeSeed::<#try_from_type>::from(
                    #ctxt.for_flattened(#id_prefix)
                  );
                  #field_name = Some(match #nvp.next_value_seed(__seed__) {
                    Ok(Ok(__intermediate__)) => {
                      // Convert from try_from type to field type
                      match <#inner_type as ::core::convert::TryFrom<_>>::try_from(__intermediate__) {
                        Ok(__val__) => Some(#val_expr),
                        Err(__err__) => {
                          #errors_ident.push(
                            InnerError::serde(
                              #ctxt.document_name,
                              #field_name_str,
                              __err__
                            )
                          );
                          None
                        }
                      }
                    }
                    Ok(Err(__errs__)) => {
                      #errors_ident.extend(__errs__);
                      None
                    }
                    Err(__err__) => {
                      #errors_ident.push(
                        InnerError::serde(
                          #ctxt.document_name,
                          #field_name_str,
                          __err__
                        )
                      );
                      None
                    }
                  });
                }
              },
            };

            // Return all names for error messages
            let mut all_names = vec![serde_name_str.clone()];
            all_names.extend(serde_aliases);

            Ok(SerdeStrategy {
                state_machine_type: None,
                state_machine_init: None,
                match_expr,
                serde_keys: SerdeKeys::Lit(all_names),
            })
        } else {
            // Note: If next_value_seed returns Err rather than Ok(Err), then I believe it means
            // that our DeserializeSeed implementation never ran, since it never does that.
            // But it's possible that the MapAccess will fail before even getting to that point,
            // and then it could return a singular D::Error. So we should not unwrap such errors.

            let match_expr = quote! {
              {
                if #field_name.is_some() {
                  #errors_ident.push(
                    InnerError::serde(
                      #ctxt.document_name,
                      #field_name_str,
                      #nvp_type::Error::duplicate_field(#serde_name_str)
                    )
                  );
                } else {
                  let __seed__ = ConfSerdeSeed::<#inner_type>::from(
                    #ctxt.for_flattened(#id_prefix)
                  );
                  #field_name = Some(match #nvp.next_value_seed(__seed__) {
                    Ok(Ok(__val__)) => {
                      Some(#val_expr)
                    }
                    Ok(Err(__errs__)) => {
                      #errors_ident.extend(__errs__);
                      None
                    }
                    Err(__err__) => {
                      #errors_ident.push(
                        InnerError::serde(
                          #ctxt.document_name,
                          #field_name_str,
                          __err__
                        )
                      );
                      None
                    }
                  });
                }
              },
            };

            // Return all names for error messages
            let mut all_names = vec![serde_name_str.clone()];
            all_names.extend(serde_aliases);

            Ok(SerdeStrategy {
                state_machine_type: None,
                state_machine_init: None,
                match_expr,
                serde_keys: SerdeKeys::Lit(all_names),
            })
        }
    }

    /// Generate debug assertions for this flatten field.
    /// Recursively calls debug_asserts on the flattened type and validates skip_short.
    pub fn gen_debug_asserts(&self, _struct_ident: &Ident) -> Result<TokenStream, Error> {
        let inner_type = if let Some(opt_type) = &self.is_optional_type {
            opt_type.clone()
        } else {
            self.field_type.clone()
        };

        // Check for positional args in flatten optional
        let positional_check = if self.is_optional_type.is_some() {
            let field_name = self.field_name.to_string();
            quote! {
                // Check for positional args in flatten optional
                for opt in <#inner_type as ::conf::Conf>::PROGRAM_OPTIONS.iter() {
                    if opt.is_positional {
                        panic!(
                            "{}",
                            ::conf::Error::positional_in_flatten_optional(
                                #field_name,
                                <#inner_type as ::conf::Conf>::get_name(),
                                &opt.id
                            )
                        );
                    }
                }
            }
        } else {
            quote! {}
        };

        // Generate skip_short validation
        let skip_short_validation = if let Some(skip_short) = &self.skip_short {
            let chars = skip_short.elements.iter().collect::<Vec<_>>();
            let field_name = self.field_name.to_string();
            let type_name = quote! { stringify!(#inner_type) };

            quote! {
                // Validate skip_short references actual short forms
                {
                    let skip_shorts = vec![#(#chars),*];
                    let mut found = vec![false; skip_shorts.len()];

                    for opt in <#inner_type as ::conf::Conf>::PROGRAM_OPTIONS.iter() {
                        if let Some(short) = opt.short_form {
                            for (idx, skip_short) in skip_shorts.iter().enumerate() {
                                if short == *skip_short {
                                    found[idx] = true;
                                }
                            }
                        }
                    }

                    let not_found: Vec<char> = skip_shorts.iter()
                        .zip(found.iter())
                        .filter_map(|(c, f)| if !*f { Some(*c) } else { None })
                        .collect();

                    if !not_found.is_empty() {
                        panic!(
                            "{}",
                            ::conf::Error::skip_short_not_found(
                                not_found,
                                #field_name,
                                #type_name
                            )
                        );
                    }
                }
            }
        } else {
            quote! {}
        };

        Ok(quote! {
            <#inner_type as ::conf::Conf>::debug_asserts();
            #positional_check
            #skip_short_validation
        })
    }
}

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

    #[test]
    fn test_make_long_prefix() {
        let result = make_long_prefix(&"my_field", Span::call_site()).unwrap();
        assert_eq!(result.value(), "my-field-");
    }

    #[test]
    fn test_make_env_prefix() {
        let result = make_env_prefix(&"my_field", Span::call_site()).unwrap();
        assert_eq!(result.value(), "MY_FIELD_");
    }
}