koruma-derive-core 0.7.1

Core of koruma-derive
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
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
//! Parsing logic for `#[koruma(...)]` attributes.
//!
//! This module provides types and functions for parsing koruma validation
//! attributes from syn AST nodes.

use syn::{
    Attribute, Error, Expr, Field, Fields, GenericArgument, Ident, Index, ItemStruct, Member, Path,
    PathArguments, Result, Token, Type, parenthesized,
    parse::{Parse, ParseStream},
    spanned::Spanned,
    token,
};

use syn_cfg_attr::AttributeHelpers;

/// Represents a single parsed validator: `ValidatorName(arg = value, ...)` or
/// `ValidatorName::<_>(arg = value, ...)` or `ValidatorName::<SomeType>(arg = value, ...)`
/// Also supports fully-qualified paths like `module::path::ValidatorName::<_>`.
///
/// Uses turbofish syntax (`::<>`) for type parameters, which simplifies parsing
/// and naturally handles nested generics like `Validator::<Option<Vec<T>>>`.
///
/// # Examples
///
/// ```ignore
/// // Simple validator
/// #[koruma(NonEmptyValidation)]
///
/// // Validator with type inference
/// #[koruma(RangeValidation::<_>(min = 0, max = 100))]
///
/// // Validator with explicit type
/// #[koruma(RangeValidation::<i32>(min = 0, max = 100))]
///
/// // Full path
/// #[koruma(validators::numeric::RangeValidation::<_>(min = 0))]
/// ```
#[derive(Clone, Debug)]
pub struct ValidatorAttr {
    /// The validator path, which may be a simple identifier or a full path.
    /// Examples: `StringLengthValidation`, `validators::normal::NumberRangeValidation`
    pub validator: Path,
    /// Whether the validator uses `::<_>` syntax for type inference from field type.
    /// When true, the field type is used (unwrapping Option if present).
    pub infer_type: bool,
    /// Explicit type parameter if specified (e.g., `::<f64>`, `::<Vec<_>>`)
    /// If this contains `_`, it will be substituted with the inner type from the field.
    /// Use `::<Option<_>>` to get the full Option type without unwrapping.
    pub explicit_type: Option<Type>,
    /// Key-value argument pairs passed to the validator.
    pub args: Vec<(Ident, Expr)>,
}

impl ValidatorAttr {
    const USE_TURBO_SYNTAX_MSG: &'static str = "use turbofish syntax `::<_>` to infer the type";
    /// Returns the simple name of the validator (the last segment of the path).
    /// Used for generating field names and enum variants.
    pub fn name(&self) -> &Ident {
        &self
            .validator
            .segments
            .last()
            .expect("path should have at least one segment")
            .ident
    }

    /// Returns whether this validator has any arguments.
    pub fn has_args(&self) -> bool {
        !self.args.is_empty()
    }

    /// Returns whether this validator uses type inference (`::<_>` syntax).
    pub fn uses_type_inference(&self) -> bool {
        self.infer_type
    }

    /// Returns whether this validator has an explicit type parameter.
    pub fn has_explicit_type(&self) -> bool {
        self.explicit_type.is_some()
    }
}

impl Parse for ValidatorAttr {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse validator path first; syn captures turbofish as arguments on the final segment.
        let mut validator: Path = input.parse()?;

        // Check for turbofish generic syntax: ::<_> or ::<SomeType>
        // ::<_> means "use the field type" (unwrapping Option if present)
        // ::<Option<_>> means "use the full Option type" (without unwrapping)
        // ::<Vec<_>> means "substitute _ with the inner type from the field"
        let (infer_type, explicit_type) = {
            let validator_span = validator.span();
            let last_segment = validator
                .segments
                .last_mut()
                .ok_or_else(|| Error::new(validator_span, "expected validator path"))?;

            // Strip generic args from stored validator path and parse them into fields.
            let args = std::mem::replace(&mut last_segment.arguments, PathArguments::None);
            match args {
                PathArguments::None => {
                    // User used old syntax without ::, give helpful error.
                    if input.peek(Token![<]) {
                        return Err(Error::new(input.span(), Self::USE_TURBO_SYNTAX_MSG));
                    }
                    (false, None)
                },
                PathArguments::AngleBracketed(mut angle_args) => {
                    if angle_args.colon2_token.is_none() {
                        return Err(Error::new(angle_args.span(), Self::USE_TURBO_SYNTAX_MSG));
                    }

                    if angle_args.args.len() != 1 {
                        return Err(Error::new(
                            angle_args.span(),
                            "validator type syntax expects exactly one type argument",
                        ));
                    }

                    let arg = angle_args.args.pop().expect("len checked").into_value();
                    match arg {
                        GenericArgument::Type(Type::Infer(_)) => (true, None),
                        GenericArgument::Type(ty) => (false, Some(ty)),
                        _ => Err(Error::new(
                            arg.span(),
                            "validator type syntax expects a type argument",
                        ))?,
                    }
                },
                PathArguments::Parenthesized(args) => {
                    return Err(Error::new(
                        args.span(),
                        "validator path does not support parenthesized arguments",
                    ));
                },
            }
        };

        let args = if input.peek(token::Paren) {
            let content;
            parenthesized!(content in input);

            let mut args = Vec::new();
            while !content.is_empty() {
                let name: Ident = content.parse()?;
                content.parse::<Token![=]>()?;
                let value: Expr = content.parse()?;

                args.push((name, value));

                if content.peek(Token![,]) {
                    content.parse::<Token![,]>()?;
                }
            }
            args
        } else {
            Vec::new()
        };

        Ok(ValidatorAttr {
            validator,
            infer_type,
            explicit_type,
            args,
        })
    }
}

/// Represents a parsed `#[koruma(...)]` attribute which can contain multiple validators
/// separated by commas: `#[koruma(Validator1(a = 1), Validator2(b = 2))]`
///
/// Can also include:
/// - `each(...)` modifier for collection validation
/// - `skip` to skip validation for a field
/// - `nested` to validate nested structs that also derive Koruma
/// - `newtype` to validate a newtype wrapper with transparent error access
///
/// # Examples
///
/// ```ignore
/// // Multiple validators
/// #[koruma(Validator1(a = 1), Validator2(b = 2))]
///
/// // Element validation for collections
/// #[koruma(VecValidator(min = 0), each(ElementValidator(max = 100)))]
///
/// // Skip validation
/// #[koruma(skip)]
///
/// // Nested Koruma struct
/// #[koruma(nested)]
/// ```
#[derive(Clone, Debug, Default)]
pub struct KorumaAttr {
    /// Validators applied to the field/collection itself
    pub field_validators: Vec<ValidatorAttr>,
    /// Validators applied to each element in a collection (from `each(...)`)
    pub element_validators: Vec<ValidatorAttr>,
    /// Whether this field should be skipped
    pub is_skip: bool,
    /// Whether this field is a nested Koruma struct
    pub is_nested: bool,
    /// Whether this field is a newtype wrapper (single-field struct deriving Koruma).
    /// Similar to nested, but generates a wrapper error struct with Deref for transparent access.
    pub is_newtype: bool,
}

impl KorumaAttr {
    /// Returns whether this attribute has any validators (field or element).
    pub fn has_validators(&self) -> bool {
        !self.field_validators.is_empty() || !self.element_validators.is_empty()
    }

    /// Returns whether this attribute represents a modifier (skip, nested, newtype).
    pub fn is_modifier(&self) -> bool {
        self.is_skip || self.is_nested || self.is_newtype
    }
}

impl Parse for KorumaAttr {
    fn parse(input: ParseStream) -> Result<Self> {
        // Check for skip, nested, or newtype
        if input.peek(Ident) {
            let fork = input.fork();
            let ident: Ident = fork.parse()?;
            if ident == "skip" && fork.is_empty() {
                input.parse::<Ident>()?; // consume "skip"
                return Ok(KorumaAttr {
                    field_validators: Vec::new(),
                    element_validators: Vec::new(),
                    is_skip: true,
                    is_nested: false,
                    is_newtype: false,
                });
            }
            // Check for nested
            if ident == "nested" && fork.is_empty() {
                input.parse::<Ident>()?; // consume "nested"
                return Ok(KorumaAttr {
                    field_validators: Vec::new(),
                    element_validators: Vec::new(),
                    is_skip: false,
                    is_nested: true,
                    is_newtype: false,
                });
            }
            // Check for newtype - can be standalone or followed by validators
            if ident == "newtype" {
                // Check if newtype is followed by a comma or end of input
                input.parse::<Ident>()?; // consume "newtype"

                // Check for comma followed by validators
                if input.peek(Token![,]) {
                    input.parse::<Token![,]>()?; // consume comma
                    // Continue parsing validators below
                    let mut field_validators = Vec::new();
                    let mut element_validators = Vec::new();

                    while !input.is_empty() {
                        // Check if this is an `each(...)` block
                        if input.peek(Ident) {
                            let fork = input.fork();
                            let ident: Ident = fork.parse()?;
                            if ident == "each" && fork.peek(token::Paren) {
                                input.parse::<Ident>()?; // consume "each"
                                let content;
                                parenthesized!(content in input);

                                while !content.is_empty() {
                                    element_validators.push(content.parse::<ValidatorAttr>()?);
                                    if content.peek(Token![,]) {
                                        content.parse::<Token![,]>()?;
                                    } else {
                                        break;
                                    }
                                }

                                if input.peek(Token![,]) {
                                    input.parse::<Token![,]>()?;
                                }
                                continue;
                            }
                        }

                        field_validators.push(input.parse::<ValidatorAttr>()?);
                        if input.peek(Token![,]) {
                            input.parse::<Token![,]>()?;
                        } else {
                            break;
                        }
                    }

                    return Ok(KorumaAttr {
                        field_validators,
                        element_validators,
                        is_skip: false,
                        is_nested: false,
                        is_newtype: true,
                    });
                }

                // Standalone newtype
                if input.is_empty() {
                    return Ok(KorumaAttr {
                        field_validators: Vec::new(),
                        element_validators: Vec::new(),
                        is_skip: false,
                        is_nested: false,
                        is_newtype: true,
                    });
                }
            }
        }

        let mut field_validators = Vec::new();
        let mut element_validators = Vec::new();

        // Parse comma-separated items (validators or each(...))
        while !input.is_empty() {
            // Check if this is an `each(...)` block
            if input.peek(Ident) {
                let fork = input.fork();
                let ident: Ident = fork.parse()?;
                if ident == "each" && fork.peek(token::Paren) {
                    input.parse::<Ident>()?; // consume "each"
                    let content;
                    parenthesized!(content in input);

                    // Parse validators inside each(...)
                    while !content.is_empty() {
                        element_validators.push(content.parse::<ValidatorAttr>()?);
                        if content.peek(Token![,]) {
                            content.parse::<Token![,]>()?;
                        } else {
                            break;
                        }
                    }

                    // Continue parsing after each(...)
                    if input.peek(Token![,]) {
                        input.parse::<Token![,]>()?;
                    }
                    continue;
                }
            }

            // Regular validator
            field_validators.push(input.parse::<ValidatorAttr>()?);
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            } else {
                break;
            }
        }

        Ok(KorumaAttr {
            field_validators,
            element_validators,
            is_skip: false,
            is_nested: false,
            is_newtype: false,
        })
    }
}

/// Struct-level options parsed from `#[koruma(...)]`
///
/// # Examples
///
/// ```ignore
/// // Generate try_new constructor
/// #[koruma(try_new)]
/// #[derive(Koruma)]
/// struct User { ... }
///
/// // Newtype wrapper
/// #[koruma(newtype)]
/// #[derive(Koruma)]
/// struct Email(String);
///
/// // Both options
/// #[koruma(try_new, newtype)]
/// #[derive(Koruma)]
/// struct Email(String);
///
/// // TryFrom impl for newtypes - converts inner type to validated wrapper
/// #[koruma(newtype(try_from))]
/// #[derive(Koruma)]
/// struct Email(String);
/// ```
#[derive(Clone, Debug, Default)]
pub struct StructOptions {
    /// Generate a `try_new` function that validates on construction
    pub try_new: bool,
    /// Treat this struct as a newtype (single-field wrapper).
    /// Generates an `.all()` method on the error struct that aggregates
    /// all validators from the single field.
    pub newtype: bool,
    /// Generate a `TryFrom<Inner>` impl for newtype structs.
    /// Set via `newtype(try_from)`. Implies `newtype`. Does NOT imply `try_new`.
    pub try_from: bool,
}

/// Options for the `newtype(...)` attribute.
#[derive(Clone, Debug, Default)]
pub struct NewtypeOptions {
    pub try_from: bool,
}

impl Parse for NewtypeOptions {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut options = NewtypeOptions::default();

        while !input.is_empty() {
            let ident: Ident = input.parse()?;
            match ident.to_string().as_str() {
                "try_from" => options.try_from = true,
                other => {
                    return Err(Error::new(
                        ident.span(),
                        format!("unknown newtype option: `{}`. Expected `try_from`", other),
                    ));
                },
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(options)
    }
}

impl Parse for StructOptions {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut options = StructOptions::default();

        while !input.is_empty() {
            let ident: Ident = input.parse()?;
            match ident.to_string().as_str() {
                "try_new" => options.try_new = true,
                "newtype" => {
                    options.newtype = true;
                    // Check for nested options: newtype(try_from)
                    if input.peek(syn::token::Paren) {
                        let content;
                        syn::parenthesized!(content in input);
                        let newtype_opts: NewtypeOptions = content.parse()?;
                        options.try_from = newtype_opts.try_from;
                    }
                },
                other => {
                    return Err(Error::new(
                        ident.span(),
                        format!(
                            "unknown struct-level koruma option: `{}`. Expected `try_new` or `newtype`",
                            other
                        ),
                    ));
                },
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(options)
    }
}

/// Parse struct-level `#[koruma(...)]` attributes from a list of attributes.
///
/// Returns `StructOptions::default()` if no `#[koruma(...)]` attribute is found.
pub fn parse_struct_options(attrs: &[Attribute]) -> Result<StructOptions> {
    if let Some(attr) = attrs.to_vec().find_attribute("koruma").first() {
        attr.parse_args::<StructOptions>()
    } else {
        Ok(StructOptions::default())
    }
}

/// Validation information extracted from `#[koruma(...)]` attributes.
#[derive(Clone, Debug, Default)]
pub struct ValidationInfo {
    /// Validators for the field/collection itself
    pub field_validators: Vec<ValidatorAttr>,
    /// Validators for each element in a collection
    pub element_validators: Vec<ValidatorAttr>,
    /// Whether this field is a nested Koruma struct
    pub is_nested: bool,
    /// Whether this field is a newtype wrapper
    pub is_newtype: bool,
}

/// Field information extracted from parsing `#[koruma(...)]` attributes.
///
/// This struct contains all the parsed validation information for a single field,
/// including validators, element validators (for collection), and modifier flags.
#[derive(Clone, Debug)]
pub struct FieldInfo {
    /// The field name
    pub name: Ident,
    /// The struct member access (Named or Unnamed index)
    pub member: Member,
    /// The field type
    pub ty: Type,
    /// Validation info for this field
    pub validation: ValidationInfo,
}

impl FieldInfo {
    /// Returns true if this field has element validators (uses `each(...)`)
    pub fn has_element_validators(&self) -> bool {
        !self.validation.element_validators.is_empty()
    }

    /// Returns true if this field has any validators (field or element)
    pub fn has_validators(&self) -> bool {
        !self.validation.field_validators.is_empty()
            || !self.validation.element_validators.is_empty()
    }

    /// Returns true if this field is a nested Koruma struct
    pub fn is_nested(&self) -> bool {
        self.validation.is_nested
    }

    /// Returns true if this field is a newtype wrapper
    pub fn is_newtype(&self) -> bool {
        self.validation.is_newtype
    }

    /// Returns an iterator over all validator names on this field.
    pub fn validator_names(&self) -> impl Iterator<Item = &Ident> {
        self.validation
            .field_validators
            .iter()
            .chain(self.validation.element_validators.iter())
            .map(|v| v.name())
    }
}

/// Result of parsing a field with `#[koruma(...)]` attribute.
///
/// This enum represents the three possible outcomes of parsing a field:
/// - `Valid`: The field has valid koruma validators
/// - `Skip`: The field should be skipped (no koruma attribute, or `#[koruma(skip)]`)
/// - `Error`: A parse error occurred
#[derive(Debug)]
pub enum ParseFieldResult {
    /// Field has valid koruma validators
    Valid(Box<FieldInfo>),
    /// Field should be skipped (no koruma attribute, or #[koruma(skip)])
    Skip,
    /// Parse error occurred
    Error(Error),
}

impl ParseFieldResult {
    /// Returns the field info if this is a `Valid` result.
    pub fn valid(self) -> Option<FieldInfo> {
        match self {
            ParseFieldResult::Valid(info) => Some(*info),
            _ => None,
        }
    }

    /// Returns the error if this is an `Error` result.
    pub fn error(self) -> Option<Error> {
        match self {
            ParseFieldResult::Error(e) => Some(e),
            _ => None,
        }
    }

    /// Returns true if this is a `Valid` result.
    pub fn is_valid(&self) -> bool {
        matches!(self, ParseFieldResult::Valid(_))
    }

    /// Returns true if this is a `Skip` result.
    pub fn is_skip(&self) -> bool {
        matches!(self, ParseFieldResult::Skip)
    }

    /// Returns true if this is an `Error` result.
    pub fn is_error(&self) -> bool {
        matches!(self, ParseFieldResult::Error(_))
    }
}

/// Parse a single field and extract its koruma validation information.
///
/// This function handles:
/// - Multiple `#[koruma(...)]` attributes on the same field
/// - Combining validators from multiple attributes
/// - Detecting duplicate validators
/// - The `skip`, `nested`, and `newtype` modifiers
///
/// # Returns
///
/// - `ParseFieldResult::Valid(FieldInfo)` if the field has validators
/// - `ParseFieldResult::Skip` if the field has no koruma attributes or is marked with `skip`
/// - `ParseFieldResult::Error(Error)` if parsing failed (e.g., duplicate validators)
/// - `ParseFieldResult::Valid(FieldInfo)` if the field has validators
/// - `ParseFieldResult::Skip` if the field has no koruma attributes or is marked with `skip`
/// - `ParseFieldResult::Error(Error)` if parsing failed (e.g., duplicate validators)
pub fn parse_field(field: &Field, index: usize) -> ParseFieldResult {
    let (name, member) = match field.ident.clone() {
        Some(ident) => (ident.clone(), Member::Named(ident)),
        None => (
            quote::format_ident!("_{}", index),
            Member::Unnamed(Index::from(index)),
        ),
    };
    let ty = field.ty.clone();

    // Collect validators from ALL #[koruma(...)] attributes on this field
    let mut all_field_validators = Vec::new();
    let mut all_element_validators = Vec::new();
    let mut is_skip = false;
    let mut is_nested = false;
    let mut is_newtype = false;

    // Track seen validator names to detect duplicates
    let mut seen_field_validators = std::collections::HashSet::new();
    let mut seen_element_validators = std::collections::HashSet::new();

    for attr in field.attrs.to_vec().find_attribute("koruma") {
        // Parse the attribute content
        let parsed: Result<KorumaAttr> = attr.parse_args::<KorumaAttr>();

        match parsed {
            Ok(koruma_attr) => {
                // Check for skip - if any attribute says skip, skip the field
                if koruma_attr.is_skip {
                    is_skip = true;
                    continue;
                }
                // Check for nested
                if koruma_attr.is_nested {
                    is_nested = true;
                    continue;
                }
                // Check for newtype
                if koruma_attr.is_newtype {
                    is_newtype = true;
                    // Don't continue here - newtype can have validators too
                    // e.g., #[koruma(newtype, RequiredValidation)]
                }
                // Collect validators from this attribute, checking for duplicates
                for validator in koruma_attr.field_validators {
                    let validator_name = validator.name().to_string();
                    if !seen_field_validators.insert(validator_name.clone()) {
                        return ParseFieldResult::Error(Error::new(
                            validator.validator.span(),
                            format!(
                                "duplicate validator `{}` on field `{}`",
                                validator_name, name
                            ),
                        ));
                    }
                    all_field_validators.push(validator);
                }
                for validator in koruma_attr.element_validators {
                    let validator_name = validator.name().to_string();
                    if !seen_element_validators.insert(validator_name.clone()) {
                        return ParseFieldResult::Error(Error::new(
                            validator.validator.span(),
                            format!(
                                "duplicate element validator `{}` on field `{}`",
                                validator_name, name
                            ),
                        ));
                    }
                    all_element_validators.push(validator);
                }
            },
            Err(e) => {
                return ParseFieldResult::Error(e);
            },
        }
    }

    // If skip was specified, skip the field
    if is_skip {
        return ParseFieldResult::Skip;
    }

    // Check for nested
    if is_nested {
        return ParseFieldResult::Valid(Box::new(FieldInfo {
            name,
            member: member.clone(),
            ty,
            validation: ValidationInfo {
                field_validators: all_field_validators,
                element_validators: all_element_validators,
                is_nested: true,
                is_newtype: false,
            },
        }));
    }

    // Check for newtype
    if is_newtype {
        return ParseFieldResult::Valid(Box::new(FieldInfo {
            name,
            member: member.clone(),
            ty,
            validation: ValidationInfo {
                field_validators: all_field_validators,
                element_validators: all_element_validators,
                is_nested: false,
                is_newtype: true,
            },
        }));
    }

    // Must have at least one validator or modifier
    if all_field_validators.is_empty() && all_element_validators.is_empty() {
        return ParseFieldResult::Skip;
    }

    ParseFieldResult::Valid(Box::new(FieldInfo {
        name,
        member: member.clone(),
        ty,
        validation: ValidationInfo {
            field_validators: all_field_validators,
            element_validators: all_element_validators,
            is_nested: false,
            is_newtype: false,
        },
    }))
}

/// Find the field marked with `#[koruma(value)]` and return its name and type.
///
/// This is used by the `#[koruma::validator]` attribute macro to find which
/// field should receive the value being validated.
pub fn find_value_field(input: &ItemStruct) -> Option<(Ident, Type)> {
    if let Fields::Named(ref fields) = input.fields {
        for field in &fields.named {
            if let Some(attr) = field.attrs.to_vec().find_attribute("koruma").first()
                && let Ok(ident) = attr.parse_args::<Ident>()
                && ident == "value"
            {
                return Some((field.ident.clone().unwrap(), field.ty.clone()));
            }
        }
    }
    None
}

/// Parsed showcase attribute: `#[showcase(name = "...", description = "...", create = |input| { ... })]`
///
/// The `create` closure takes a `&str` and returns the validator instance.
/// Optional `input_type` can be "text" (default) or "numeric".
/// Optional `module` can be "string", "format", "numeric", "collection", or "general".
#[cfg(feature = "internal-showcase")]
#[derive(Clone, Debug)]
pub struct ShowcaseAttr {
    pub name: syn::LitStr,
    pub description: syn::LitStr,
    pub create: syn::ExprClosure,
    pub input_type: Option<Ident>,
    pub module: Option<syn::LitStr>,
}

#[cfg(feature = "internal-showcase")]
impl Parse for ShowcaseAttr {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut name: Option<syn::LitStr> = None;
        let mut description: Option<syn::LitStr> = None;
        let mut create: Option<syn::ExprClosure> = None;
        let mut input_type: Option<Ident> = None;
        let mut module: Option<syn::LitStr> = None;

        while !input.is_empty() {
            let ident: Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match ident.to_string().as_str() {
                "name" => {
                    name = Some(input.parse()?);
                },
                "description" => {
                    description = Some(input.parse()?);
                },
                "create" => {
                    create = Some(input.parse()?);
                },
                "input_type" => {
                    input_type = Some(input.parse()?);
                },
                "module" => {
                    module = Some(input.parse()?);
                },
                other => {
                    return Err(Error::new(
                        ident.span(),
                        format!("unknown showcase attribute: {}", other),
                    ));
                },
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(ShowcaseAttr {
            name: name
                .ok_or_else(|| Error::new(input.span(), "showcase requires `name` attribute"))?,
            description: description.ok_or_else(|| {
                Error::new(input.span(), "showcase requires `description` attribute")
            })?,
            create: create
                .ok_or_else(|| Error::new(input.span(), "showcase requires `create` attribute"))?,
            input_type,
            module,
        })
    }
}

/// Find and parse showcase attribute from struct
#[cfg(feature = "internal-showcase")]
pub fn find_showcase_attr(input: &ItemStruct) -> Option<ShowcaseAttr> {
    for attr in &input.attrs {
        if attr.path().is_ident("showcase")
            && let Ok(parsed) = attr.parse_args::<ShowcaseAttr>()
        {
            return Some(parsed);
        }
    }
    None
}