vld 0.3.0

Type-safe runtime validation library for Rust, inspired by Zod
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
/// Helper macro to resolve a field's JSON key.
///
/// If a rename literal is provided, use it; otherwise fall back to the field name.
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_resolve_key {
    ($default:expr) => {
        $default
    };
    ($default:expr, $override:expr) => {
        $override
    };
}

/// Define a validated struct with field-level schemas.
///
/// This macro generates:
/// - A regular Rust struct with the specified fields and types
/// - A `parse()` method that validates input and constructs the struct
/// - A `parse_value()` method for direct `serde_json::Value` input
/// - An implementation of [`VldParse`](crate::schema::VldParse) for use with framework extractors
///
/// # Syntax
///
/// ```ignore
/// vld::schema! {
///     #[derive(Debug, Clone)]
///     pub struct MyStruct {
///         pub field_name: FieldType => schema_expression,
///         pub renamed_field: FieldType as "jsonKey" => schema_expression,
///         // ...
///     }
/// }
/// ```
///
/// Each field has the format: `name: Type [as "json_key"] => schema`.
/// The optional `as "json_key"` overrides the JSON property name used for parsing.
///
/// # Example
///
/// ```
/// use vld::prelude::*;
///
/// vld::schema! {
///     #[derive(Debug)]
///     pub struct User {
///         pub name: String => vld::string().min(2).max(50),
///         pub age: Option<i64> => vld::number().int().min(0).optional(),
///         pub tags: Vec<String> => vld::array(vld::string()).max_len(5)
///             .with_default(vec![]),
///     }
/// }
///
/// let user = User::parse(r#"{"name": "Alice", "age": 30}"#).unwrap();
/// assert_eq!(user.name, "Alice");
/// assert_eq!(user.age, Some(30));
/// assert!(user.tags.is_empty());
/// ```
///
/// # Renamed Fields
///
/// ```ignore
/// vld::schema! {
///     pub struct ApiResponse {
///         pub first_name: String as "firstName" => vld::string().min(1),
///         pub last_name: String as "lastName" => vld::string().min(1),
///     }
/// }
///
/// // Parses from camelCase JSON:
/// let r = ApiResponse::parse(r#"{"firstName": "John", "lastName": "Doe"}"#).unwrap();
/// assert_eq!(r.first_name, "John");
/// ```
///
/// # Nested Structs
///
/// Use [`nested()`](crate::nested) to compose schemas:
///
/// ```ignore
/// vld::schema! {
///     pub struct Address {
///         pub city: String => vld::string().min(1),
///     }
/// }
///
/// vld::schema! {
///     pub struct User {
///         pub name: String => vld::string(),
///         pub address: Address => vld::nested(Address::parse_value),
///     }
/// }
/// ```
#[macro_export]
macro_rules! schema {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            $(
                $(#[$field_meta:meta])*
                $field_vis:vis $field_name:ident : $field_type:ty $(as $rename:literal)? => $schema:expr
            ),* $(,)?
        }
    ) => {
        $(#[$meta])*
        $vis struct $name {
            $(
                $(#[$field_meta])*
                $field_vis $field_name: $field_type,
            )*
        }

        impl $name {
            /// Parse and validate input data into this struct.
            ///
            /// Accepts any type implementing [`VldInput`]: JSON strings, file paths,
            /// `serde_json::Value`, byte slices, etc.
            pub fn parse<__VldInputT: $crate::input::VldInput + ?Sized>(
                input: &__VldInputT,
            ) -> ::std::result::Result<$name, $crate::error::VldError> {
                let __vld_json = <__VldInputT as $crate::input::VldInput>::to_json_value(input)?;
                Self::parse_value(&__vld_json)
            }

            /// Parse and validate directly from a `serde_json::Value`.
            pub fn parse_value(
                __vld_json: &$crate::serde_json::Value,
            ) -> ::std::result::Result<$name, $crate::error::VldError> {
                use $crate::schema::VldSchema as _;

                let __vld_obj = __vld_json.as_object().ok_or_else(|| {
                    $crate::error::VldError::single(
                        $crate::error::IssueCode::InvalidType {
                            expected: ::std::string::String::from("object"),
                            received: $crate::error::value_type_name(__vld_json),
                        },
                        ::std::format!(
                            "Expected object, received {}",
                            $crate::error::value_type_name(__vld_json)
                        ),
                    )
                })?;

                let mut __vld_errors = $crate::error::VldError::new();

                $(
                    #[allow(non_snake_case)]
                    let $field_name: ::std::option::Option<$field_type> = {
                        let __vld_field_schema = $schema;
                        let __vld_key = $crate::__vld_resolve_key!(
                            stringify!($field_name) $(, $rename)?
                        );
                        let __vld_field_value = __vld_obj
                            .get(__vld_key)
                            .unwrap_or(&$crate::serde_json::Value::Null);
                        match __vld_field_schema.parse_value(__vld_field_value) {
                            ::std::result::Result::Ok(v) => ::std::option::Option::Some(v),
                            ::std::result::Result::Err(e) => {
                                __vld_errors = $crate::error::VldError::merge(
                                    __vld_errors,
                                    $crate::error::VldError::with_prefix(
                                        e,
                                        $crate::error::PathSegment::Field(
                                            ::std::string::String::from(__vld_key),
                                        ),
                                    ),
                                );
                                ::std::option::Option::None
                            }
                        }
                    };
                )*

                if !$crate::error::VldError::is_empty(&__vld_errors) {
                    return ::std::result::Result::Err(__vld_errors);
                }

                ::std::result::Result::Ok($name {
                    $(
                        $field_name: $field_name.unwrap(),
                    )*
                })
            }

        }

        impl $crate::schema::VldParse for $name {
            fn vld_parse_value(
                value: &$crate::serde_json::Value,
            ) -> ::std::result::Result<Self, $crate::error::VldError> {
                Self::parse_value(value)
            }
        }


        $crate::__vld_if_serialize! {
            impl $name {
                /// Validate an existing Rust value that can be serialized to JSON.
                ///
                /// The value is serialized via `serde`, then validated against the
                /// schema. Returns `Ok(())` on success, `Err(VldError)` with all
                /// issues on failure.
                ///
                /// Requires the `serialize` feature.
                pub fn validate<__VldT: $crate::serde::Serialize>(
                    instance: &__VldT,
                ) -> ::std::result::Result<(), $crate::error::VldError> {
                    let __vld_json = $crate::serde_json::to_value(instance).map_err(|e| {
                        $crate::error::VldError::single(
                            $crate::error::IssueCode::ParseError,
                            ::std::format!("Serialization error: {}", e),
                        )
                    })?;
                    let _ = Self::parse_value(&__vld_json)?;
                    ::std::result::Result::Ok(())
                }

                /// Check if a value is valid against the schema.
                ///
                /// Shorthand for `validate(instance).is_ok()`.
                ///
                /// Requires the `serialize` feature.
                pub fn is_valid<__VldT: $crate::serde::Serialize>(instance: &__VldT) -> bool {
                    Self::validate(instance).is_ok()
                }
            }
        }

        $crate::__vld_if_openapi! {
            impl $name {
                /// Generate a JSON Schema / OpenAPI 3.1 representation of this struct.
                ///
                /// Requires the `openapi` feature.
                pub fn json_schema() -> $crate::serde_json::Value {
                    use $crate::json_schema::JsonSchema as _;
                    let mut __vld_properties = $crate::serde_json::Map::new();
                    let mut __vld_required: ::std::vec::Vec<::std::string::String> =
                        ::std::vec::Vec::new();

                    $(
                        {
                            let __vld_field_schema = $schema;
                            let __vld_key = $crate::__vld_resolve_key!(
                                stringify!($field_name) $(, $rename)?
                            );
                            __vld_properties.insert(
                                ::std::string::String::from(__vld_key),
                                __vld_field_schema.json_schema(),
                            );
                            __vld_required.push(
                                ::std::string::String::from(__vld_key),
                            );
                        }
                    )*

                    $crate::serde_json::json!({
                        "type": "object",
                        "required": __vld_required,
                        "properties": $crate::serde_json::Value::Object(__vld_properties),
                    })
                }

                /// Wrap `json_schema()` in a minimal OpenAPI 3.1 document.
                ///
                /// Requires the `openapi` feature.
                pub fn to_openapi_document() -> $crate::serde_json::Value {
                    $crate::json_schema::to_openapi_document(stringify!($name), &Self::json_schema())
                }

                /// Collect `(name, json_schema_fn)` pairs for all nested schemas
                /// used by fields of this struct.
                ///
                /// Used by `vld-utoipa`'s `impl_to_schema!` to automatically register
                /// nested types as OpenAPI components.
                #[doc(hidden)]
                pub fn __vld_nested_schemas()
                    -> ::std::vec::Vec<$crate::json_schema::NestedSchemaEntry>
                {
                    use $crate::json_schema::CollectNestedSchemas as _;
                    let mut __vld_out: ::std::vec::Vec<$crate::json_schema::NestedSchemaEntry> =
                        ::std::vec::Vec::new();

                    $(
                        {
                            let __vld_field_schema = $schema;
                            __vld_field_schema.collect_nested_schemas(&mut __vld_out);
                        }
                    )*

                    __vld_out
                }
            }
        }
    };
}

/// Generate `validate_fields()` and `parse_lenient()` methods for a struct
/// previously defined with [`schema!`].
///
/// Syntax mirrors `schema!`, but without visibility/attributes:
///
/// ```ignore
/// vld::impl_validate_fields!(User {
///     name: String => vld::string().min(2),
///     age: i64     => vld::number().int(),
/// });
/// ```
///
/// Fields can also use `as "json_key"` to match a renamed JSON property:
///
/// ```ignore
/// vld::impl_validate_fields!(User {
///     first_name: String as "firstName" => vld::string().min(2),
/// });
/// ```
///
/// Generated methods:
///
/// - **`validate_fields(input)`** — validate each field, return `Vec<FieldResult>`
/// - **`parse_lenient(input)`** — build the struct even if some fields fail
///   (uses `Default` for invalid fields), returns [`ParseResult<Self>`](crate::error::ParseResult)
///
/// The returned [`ParseResult`](crate::error::ParseResult) can be inspected,
/// converted to JSON, or saved to a file at any time via `.save_to_file(path)`.
///
/// **Requires:**
/// - Field output types: `serde::Serialize`
/// - For `parse_lenient`: field types also need `Default`
/// - For `save_to_file` / `to_json_string`: the struct needs `serde::Serialize`
#[macro_export]
macro_rules! impl_validate_fields {
    (
        $name:ident {
            $( $field_name:ident : $field_type:ty $(as $rename:literal)? => $schema:expr ),* $(,)?
        }
    ) => {
        impl $name {
            /// Validate each field individually and return per-field results.
            ///
            /// Unlike `parse()`, this does **not** fail fast — every field is
            /// validated and you see which fields passed and which failed.
            pub fn validate_fields<__VldInputT: $crate::input::VldInput + ?Sized>(
                input: &__VldInputT,
            ) -> ::std::result::Result<
                ::std::vec::Vec<$crate::error::FieldResult>,
                $crate::error::VldError,
            > {
                let __vld_json = <__VldInputT as $crate::input::VldInput>::to_json_value(input)?;
                Self::validate_fields_value(&__vld_json)
            }

            /// Validate each field individually from a `serde_json::Value`.
            pub fn validate_fields_value(
                __vld_json: &$crate::serde_json::Value,
            ) -> ::std::result::Result<
                ::std::vec::Vec<$crate::error::FieldResult>,
                $crate::error::VldError,
            > {
                let __vld_obj = __vld_json.as_object().ok_or_else(|| {
                    $crate::error::VldError::single(
                        $crate::error::IssueCode::InvalidType {
                            expected: ::std::string::String::from("object"),
                            received: $crate::error::value_type_name(__vld_json),
                        },
                        ::std::format!(
                            "Expected object, received {}",
                            $crate::error::value_type_name(__vld_json)
                        ),
                    )
                })?;

                let mut __vld_results: ::std::vec::Vec<$crate::error::FieldResult> =
                    ::std::vec::Vec::new();

                $(
                    {
                        let __vld_field_schema = $schema;
                        let __vld_key = $crate::__vld_resolve_key!(
                            stringify!($field_name) $(, $rename)?
                        );
                        let __vld_field_value = __vld_obj
                            .get(__vld_key)
                            .unwrap_or(&$crate::serde_json::Value::Null);

                        let __vld_result = $crate::object::DynSchema::dyn_parse(
                            &__vld_field_schema,
                            __vld_field_value,
                        );

                        __vld_results.push($crate::error::FieldResult {
                            name: ::std::string::String::from(__vld_key),
                            input: __vld_field_value.clone(),
                            result: __vld_result,
                        });
                    }
                )*

                ::std::result::Result::Ok(__vld_results)
            }

            /// Parse leniently: build the struct even when some fields fail.
            ///
            /// - Valid fields get their parsed value.
            /// - Invalid fields fall back to `Default::default()`.
            ///
            /// Returns a [`ParseResult`](crate::error::ParseResult) that wraps
            /// the struct and per-field diagnostics. You can inspect it, convert
            /// to JSON, or save to a file whenever you need.
            pub fn parse_lenient<__VldInputT: $crate::input::VldInput + ?Sized>(
                input: &__VldInputT,
            ) -> ::std::result::Result<
                $crate::error::ParseResult<$name>,
                $crate::error::VldError,
            > {
                let __vld_json = <__VldInputT as $crate::input::VldInput>::to_json_value(input)?;
                Self::parse_lenient_value(&__vld_json)
            }

            /// Parse leniently from a `serde_json::Value`.
            pub fn parse_lenient_value(
                __vld_json: &$crate::serde_json::Value,
            ) -> ::std::result::Result<
                $crate::error::ParseResult<$name>,
                $crate::error::VldError,
            > {
                use $crate::schema::VldSchema as _;

                let __vld_obj = __vld_json.as_object().ok_or_else(|| {
                    $crate::error::VldError::single(
                        $crate::error::IssueCode::InvalidType {
                            expected: ::std::string::String::from("object"),
                            received: $crate::error::value_type_name(__vld_json),
                        },
                        ::std::format!(
                            "Expected object, received {}",
                            $crate::error::value_type_name(__vld_json)
                        ),
                    )
                })?;

                let mut __vld_results: ::std::vec::Vec<$crate::error::FieldResult> =
                    ::std::vec::Vec::new();

                $(
                    #[allow(non_snake_case)]
                    let $field_name: $field_type = {
                        let __vld_field_schema = $schema;
                        let __vld_key = $crate::__vld_resolve_key!(
                            stringify!($field_name) $(, $rename)?
                        );
                        let __vld_field_value = __vld_obj
                            .get(__vld_key)
                            .unwrap_or(&$crate::serde_json::Value::Null);

                        match __vld_field_schema.parse_value(__vld_field_value) {
                            ::std::result::Result::Ok(v) => {
                                let __json_repr = $crate::serde_json::to_value(&v)
                                    .unwrap_or_else(|_| __vld_field_value.clone());
                                __vld_results.push($crate::error::FieldResult {
                                    name: ::std::string::String::from(__vld_key),
                                    input: __vld_field_value.clone(),
                                    result: ::std::result::Result::Ok(__json_repr),
                                });
                                v
                            }
                            ::std::result::Result::Err(e) => {
                                __vld_results.push($crate::error::FieldResult {
                                    name: ::std::string::String::from(__vld_key),
                                    input: __vld_field_value.clone(),
                                    result: ::std::result::Result::Err(e),
                                });
                                <$field_type as ::std::default::Default>::default()
                            }
                        }
                    };
                )*

                let __vld_struct = $name {
                    $( $field_name, )*
                };

                ::std::result::Result::Ok(
                    $crate::error::ParseResult::new(__vld_struct, __vld_results)
                )
            }
        }
    };
}

/// Combined macro: generates the struct, `parse()`, **and** `validate_fields()` /
/// `parse_lenient()` in a single declaration — no need to repeat field schemas.
///
/// This is equivalent to calling `schema!` + `impl_validate_fields!` together.
///
/// **Extra requirements** compared to `schema!`:
/// - All field types must implement `serde::Serialize` (for per-field JSON output)
/// - All field types must implement `Default` (for lenient fallback values)
///
/// # Example
///
/// ```ignore
/// vld::schema_validated! {
///     #[derive(Debug, serde::Serialize)]
///     pub struct User {
///         pub name: String => vld::string().min(2),
///         pub age: Option<i64> => vld::number().int().optional(),
///     }
/// }
///
/// // Has parse(), validate_fields(), parse_lenient(), etc.
/// let result = User::parse_lenient(r#"{"name":"X"}"#).unwrap();
/// result.save_to_file(std::path::Path::new("out.json")).unwrap();
/// ```
#[macro_export]
macro_rules! schema_validated {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            $(
                $(#[$field_meta:meta])*
                $field_vis:vis $field_name:ident : $field_type:ty $(as $rename:literal)? => $schema:expr
            ),* $(,)?
        }
    ) => {
        // 1. Generate the struct + parse/parse_value (same as schema!)
        $crate::schema! {
            $(#[$meta])*
            $vis struct $name {
                $(
                    $(#[$field_meta])*
                    $field_vis $field_name : $field_type $(as $rename)? => $schema
                ),*
            }
        }

        // 2. Generate validate_fields + parse_lenient (same as impl_validate_fields!)
        $crate::impl_validate_fields!($name {
            $( $field_name : $field_type $(as $rename)? => $schema ),*
        });
    };
}

/// Attach validation rules to an **existing** struct.
///
/// Unlike [`schema!`] which creates the struct, this macro takes a struct you
/// already have and generates `validate()` and `is_valid()` instance methods.
///
/// The struct must implement `serde::Serialize`.
///
/// The struct does **not** need `#[derive(Serialize)]` or `#[derive(Debug)]` —
/// each field is serialized individually (standard types like `String`, `f64`,
/// `Vec<T>` already implement `Serialize`).
///
/// # Example
///
/// ```
/// use vld::prelude::*;
///
/// // No Serialize or Debug required on the struct itself
/// struct Product {
///     name: String,
///     price: f64,
///     tags: Vec<String>,
/// }
///
/// vld::impl_rules!(Product {
///     name => vld::string().min(2).max(100),
///     price => vld::number().positive(),
///     tags => vld::array(vld::string().min(1)).max_len(10),
/// });
///
/// let p = Product {
///     name: "Widget".into(),
///     price: 9.99,
///     tags: vec!["sale".into()],
/// };
/// assert!(p.is_valid());
///
/// let bad = Product {
///     name: "X".into(),
///     price: -1.0,
///     tags: vec![],
/// };
/// assert!(!bad.is_valid());
/// let err = bad.validate().unwrap_err();
/// assert!(err.issues.len() >= 2);
/// ```
#[macro_export]
macro_rules! impl_rules {
    (
        $name:ident {
            $( $field:ident => $schema:expr ),* $(,)?
        }
    ) => {
        impl $name {
            /// Validate this instance against the declared rules.
            ///
            /// Each field is serialized to JSON individually and checked
            /// against its schema. All errors are accumulated.
            pub fn validate(&self) -> ::std::result::Result<(), $crate::error::VldError> {
                use $crate::schema::VldSchema as _;
                let mut __vld_errors = $crate::error::VldError::new();

                $(
                    {
                        let __vld_field_json = $crate::serde_json::to_value(&self.$field)
                            .map_err(|e| {
                                $crate::error::VldError::single(
                                    $crate::error::IssueCode::ParseError,
                                    ::std::format!(
                                        "Serialization error for field '{}': {}",
                                        stringify!($field), e
                                    ),
                                )
                            });
                        match __vld_field_json {
                            ::std::result::Result::Ok(ref __vld_val) => {
                                let __vld_field_schema = $schema;
                                if let ::std::result::Result::Err(e) =
                                    __vld_field_schema.parse_value(__vld_val)
                                {
                                    __vld_errors = $crate::error::VldError::merge(
                                        __vld_errors,
                                        $crate::error::VldError::with_prefix(
                                            e,
                                            $crate::error::PathSegment::Field(
                                                ::std::string::String::from(stringify!($field)),
                                            ),
                                        ),
                                    );
                                }
                            }
                            ::std::result::Result::Err(e) => {
                                __vld_errors = $crate::error::VldError::merge(
                                    __vld_errors,
                                    $crate::error::VldError::with_prefix(
                                        e,
                                        $crate::error::PathSegment::Field(
                                            ::std::string::String::from(stringify!($field)),
                                        ),
                                    ),
                                );
                            }
                        }
                    }
                )*

                if __vld_errors.is_empty() {
                    ::std::result::Result::Ok(())
                } else {
                    ::std::result::Result::Err(__vld_errors)
                }
            }

            /// Check if this instance passes all validation rules.
            pub fn is_valid(&self) -> bool {
                self.validate().is_ok()
            }
        }
    };
}

/// Generate `impl Default` for a struct created by [`schema!`].
///
/// Use this instead of `#[derive(Default)]` to automatically generate a
/// `Default` implementation bounded on all field types implementing `Default`.
///
/// # Example
///
/// ```
/// use vld::prelude::*;
///
/// vld::schema! {
///     #[derive(Debug)]
///     pub struct Config {
///         pub host: String => vld::string().with_default("localhost".into()),
///         pub port: Option<i64> => vld::number().int().optional(),
///         pub tags: Vec<String> => vld::array(vld::string()).with_default(vec![]),
///     }
/// }
///
/// vld::impl_default!(Config { host, port, tags });
///
/// let cfg = Config::default();
/// assert_eq!(cfg.host, "");       // String::default()
/// assert_eq!(cfg.port, None);     // Option::default()
/// assert!(cfg.tags.is_empty());   // Vec::default()
/// ```
#[macro_export]
macro_rules! impl_default {
    ($name:ident { $($field:ident),* $(,)? }) => {
        impl ::std::default::Default for $name {
            fn default() -> Self {
                Self {
                    $( $field: ::std::default::Default::default(), )*
                }
            }
        }
    };
}

/// Create a union schema from 2 or more schemas.
///
/// Dispatches to `vld::union()` for 2 schemas and `vld::union3()` for 3.
/// For 4+ schemas, unions are nested automatically.
///
/// # Examples
///
/// ```rust
/// use vld::prelude::*;
///
/// // 2 schemas
/// let s = vld::union!(vld::string(), vld::number().int());
/// assert!(s.parse(r#""hello""#).is_ok());
/// assert!(s.parse("42").is_ok());
///
/// // 3 schemas
/// let s = vld::union!(vld::string(), vld::number().int(), vld::boolean());
/// assert!(s.parse("true").is_ok());
/// ```
#[macro_export]
macro_rules! union {
    // 2 schemas
    ($a:expr, $b:expr $(,)?) => {
        $crate::union($a, $b)
    };
    // 3 schemas
    ($a:expr, $b:expr, $c:expr $(,)?) => {
        $crate::union3($a, $b, $c)
    };
    // 4 schemas — nest as union(union(a, b), union(c, d))
    ($a:expr, $b:expr, $c:expr, $d:expr $(,)?) => {
        $crate::union($crate::union($a, $b), $crate::union($c, $d))
    };
    // 5 schemas
    ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr $(,)?) => {
        $crate::union($crate::union3($a, $b, $c), $crate::union($d, $e))
    };
    // 6 schemas
    ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr $(,)?) => {
        $crate::union($crate::union3($a, $b, $c), $crate::union3($d, $e, $f))
    };
}