vespera_macro 0.3.1

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
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
//! Parser for the field-level `#[schema(...)]` attribute constraints.
//!
//! Unlike the struct-level `#[schema(name=..., ref=..., nullable)]` parsers in
//! [`super::serde_attrs`], this module reads the *validation* keys that may
//! appear on individual fields:
//!
//! ```ignore
//! #[derive(vespera::Schema)]
//! pub struct CreateUser {
//!     #[schema(min_length = 3, max_length = 32, pattern = "^[a-z]+$")]
//!     pub username: String,
//!
//!     #[schema(minimum = 0, maximum = 150)]
//!     pub age: u32,
//!
//!     #[schema(format = "email")]
//!     pub email: String,
//!
//!     #[schema(read_only, example = "abc-123")]
//!     pub id: String,
//! }
//! ```
//!
//! The extracted [`SchemaConstraints`] flow into two different consumers:
//!
//! 1. **OpenAPI emission** (`struct_schema::parse_struct_to_schema`): the
//!    constraints are merged into the per-field `Schema` literal so that
//!    `openapi.json` exposes `minLength`, `maxLength`, `pattern`, … on the
//!    field schemas.
//! 2. **`garde::Validate` emission** (`schema_impl::process_derive_schema`,
//!    behind the `validation` feature): the same constraints are translated
//!    into `garde::rules::*::apply` calls inside the generated `validate_into`
//!    method body.
//!
//! Keys that have no garde counterpart (`example`, `read_only`, `write_only`,
//! `unique_items`) are still parsed — they only affect OpenAPI output.

use syn::{Attribute, Expr, ExprLit, Lit};

/// Field-level validation / documentation constraints carried by
/// `#[schema(...)]`.
///
/// Every field is `Option<_>` so an unset key means "no constraint".  The
/// shape mirrors the corresponding fields on
/// [`vespera_core::schema::Schema`] one-for-one — keep them in sync.
#[derive(Default, Clone, Debug, PartialEq)]
pub struct SchemaConstraints {
    // ── string / array length ────────────────────────────────────────
    pub min_length: Option<usize>,
    pub max_length: Option<usize>,
    pub pattern: Option<String>,

    // ── numeric range ────────────────────────────────────────────────
    pub minimum: Option<f64>,
    pub maximum: Option<f64>,
    pub exclusive_minimum: Option<bool>,
    pub exclusive_maximum: Option<bool>,
    pub multiple_of: Option<f64>,

    // ── array constraints ────────────────────────────────────────────
    pub min_items: Option<usize>,
    pub max_items: Option<usize>,
    pub unique_items: Option<bool>,

    // ── OpenAPI annotations (no runtime validation) ──────────────────
    pub format: Option<String>,
    pub example: Option<serde_json::Value>,
    pub read_only: Option<bool>,
    pub write_only: Option<bool>,

    // ── nested validation ───────────────────────────────────────────
    /// When `Some(true)`, the field is recursively validated by
    /// invoking `garde::Validate::validate_into` on its value.  The
    /// path of any reported error is prefixed with the field name
    /// (e.g. `"address.city"`), and garde's runtime impls for
    /// `Option`, `Vec`, `HashMap`, `BTreeMap` automatically handle
    /// unwrapping / iteration.  This corresponds to
    /// `#[garde(dive)]` semantics and is opt-in to avoid accidental
    /// trait-bound failures on field types that don't implement
    /// `garde::Validate` (e.g. `chrono::DateTime`, `uuid::Uuid`,
    /// most third-party newtypes).
    pub dive: Option<bool>,

    // ── schema-generation override ───────────────────────────────────
    /// When `Some(true)`, the field's OpenAPI schema is forced to the
    /// generic `{type: "object"}` regardless of its Rust type, AND the
    /// compile-time `#[derive(Schema)]` leaf-type assertion is skipped
    /// for this field.  Use this to opt a field out of strict
    /// "every-custom-type-must-derive-Schema" checking when the field
    /// is intentionally arbitrary / opaque JSON.  Bare form
    /// `#[schema(any)]` sets it to `true`; an explicit
    /// `#[schema(any = false)]` is also accepted.
    pub any: Option<bool>,
}

impl SchemaConstraints {
    /// `true` when no constraint keys were present on the field.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.min_length.is_none()
            && self.max_length.is_none()
            && self.pattern.is_none()
            && self.minimum.is_none()
            && self.maximum.is_none()
            && self.exclusive_minimum.is_none()
            && self.exclusive_maximum.is_none()
            && self.multiple_of.is_none()
            && self.min_items.is_none()
            && self.max_items.is_none()
            && self.unique_items.is_none()
            && self.format.is_none()
            && self.example.is_none()
            && self.read_only.is_none()
            && self.write_only.is_none()
            && self.dive.is_none()
            && self.any.is_none()
    }

    /// `true` when the field is marked `#[schema(any)]` (intentionally
    /// opaque object — skips the derive-Schema leaf-type assertion AND
    /// overrides the emitted schema to `{type: "object"}`).
    #[must_use]
    pub fn is_any(&self) -> bool {
        self.any == Some(true)
    }

    /// `true` when at least one constraint produces a `garde` runtime rule
    /// (excludes pure-OpenAPI annotations such as `example` / `read_only` /
    /// `write_only` / `unique_items`).
    ///
    /// Consumed by `garde_emit::emit_garde_validate` (gated on the
    /// `validation` feature) and by the unit tests below.  When the macro
    /// crate is compiled with default features (e.g. during
    /// `cargo publish --dry-run`), the call site in `garde_emit` is
    /// stripped out and only the tests reference this method — so
    /// silence `dead_code` only in that configuration.
    #[must_use]
    #[cfg_attr(not(feature = "validation"), allow(dead_code))]
    pub fn has_runtime_rule(&self) -> bool {
        self.min_length.is_some()
            || self.max_length.is_some()
            || self.pattern.is_some()
            || self.minimum.is_some()
            || self.maximum.is_some()
            || self.exclusive_minimum.is_some()
            || self.exclusive_maximum.is_some()
            || self.multiple_of.is_some()
            || self.min_items.is_some()
            || self.max_items.is_some()
            || matches!(
                self.format.as_deref(),
                Some("email" | "uri" | "url" | "ipv4" | "ipv6" | "ip")
            )
            || self.dive == Some(true)
    }
}

/// Extract all field-level `#[schema(...)]` validation / documentation
/// constraints from `attrs`.
///
/// Unknown keys are **silently ignored** so that struct-level keys
/// (`name`, `ref`, `nullable`) and future additions don't break this
/// parser when it walks a struct-level `#[schema(...)]` attribute.  A
/// **recognized** key with a malformed value is an error: silently dropping
/// known constraints makes both OpenAPI output and generated garde validators
/// lie about user intent.
#[must_use]
pub fn extract_schema_constraints(attrs: &[Attribute]) -> SchemaConstraints {
    try_extract_schema_constraints(attrs).unwrap_or_default()
}

/// Fallible variant used by macro entry points to emit `compile_error!` for
/// malformed values of known `#[schema(...)]` keys.
pub fn try_extract_schema_constraints(attrs: &[Attribute]) -> syn::Result<SchemaConstraints> {
    let mut out = SchemaConstraints::default();
    for attr in attrs {
        if !attr.path().is_ident("schema") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            // ── string / array length ────────────────────────────────
            if meta.path.is_ident("min_length") {
                out.min_length = Some(parse_usize(&meta)?);
            } else if meta.path.is_ident("max_length") {
                out.max_length = Some(parse_usize(&meta)?);
            } else if meta.path.is_ident("pattern") {
                out.pattern = Some(parse_str(&meta)?);
            }
            // ── numeric range ────────────────────────────────────────
            else if meta.path.is_ident("minimum") {
                out.minimum = Some(parse_f64(&meta)?);
            } else if meta.path.is_ident("maximum") {
                out.maximum = Some(parse_f64(&meta)?);
            } else if meta.path.is_ident("exclusive_minimum") {
                out.exclusive_minimum = Some(parse_bool_or_default_true(&meta)?);
            } else if meta.path.is_ident("exclusive_maximum") {
                out.exclusive_maximum = Some(parse_bool_or_default_true(&meta)?);
            } else if meta.path.is_ident("multiple_of") {
                out.multiple_of = Some(parse_f64(&meta)?);
            }
            // ── array constraints ────────────────────────────────────
            else if meta.path.is_ident("min_items") {
                out.min_items = Some(parse_usize(&meta)?);
            } else if meta.path.is_ident("max_items") {
                out.max_items = Some(parse_usize(&meta)?);
            } else if meta.path.is_ident("unique_items") {
                out.unique_items = Some(parse_bool_or_default_true(&meta)?);
            }
            // ── OpenAPI annotations ──────────────────────────────────
            else if meta.path.is_ident("format") {
                out.format = Some(parse_str(&meta)?);
            } else if meta.path.is_ident("example") {
                out.example = Some(parse_example_value(&meta)?);
            } else if meta.path.is_ident("read_only") {
                out.read_only = Some(parse_bool_or_default_true(&meta)?);
            } else if meta.path.is_ident("write_only") {
                out.write_only = Some(parse_bool_or_default_true(&meta)?);
            } else if meta.path.is_ident("dive") {
                // Opt-in recursive validation.  Mirrors `#[garde(dive)]`:
                // emits a `Validate::validate_into` call so nested
                // structs, `Vec<Validate>`, `Option<Validate>`,
                // `HashMap<_, Validate>` are validated transparently
                // and errors carry dotted paths like "address.city".
                out.dive = Some(parse_bool_or_default_true(&meta)?);
            } else if meta.path.is_ident("any") {
                // Bare `#[schema(any)]` (or explicit `any = true/false`)
                // opts the field out of strict schema enforcement: the
                // emitted schema is `{type: "object"}` (intentionally
                // opaque arbitrary JSON), and the derive-Schema
                // compile-time leaf-type assertion is skipped for
                // this field. Use for fields whose Rust type is some
                // custom shape the OpenAPI document is meant to leave
                // unspecified.
                out.any = Some(parse_bool_or_default_true(&meta)?);
            } else {
                // Unknown key — could be a struct-level key like `name`,
                // `ref`, `nullable`, `default` that lives on the same
                // `#[schema(...)]` attribute.  Consume any `= value`
                // payload so `parse_nested_meta` doesn't fail at the
                // trailing comma.
                if let Ok(value) = meta.value() {
                    let _: syn::Expr = value.parse()?;
                }
            }
            Ok(())
        })?;
    }
    Ok(out)
}

// ── primitive value helpers ──────────────────────────────────────────

fn parse_usize(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<usize> {
    let lit: syn::LitInt = meta.value()?.parse()?;
    lit.base10_parse::<usize>()
}

fn parse_f64(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<f64> {
    let value = meta.value()?;
    let expr: Expr = value.parse()?;
    match expr {
        Expr::Lit(ExprLit {
            lit: Lit::Float(f), ..
        }) => f.base10_parse::<f64>(),
        Expr::Lit(ExprLit {
            lit: Lit::Int(i), ..
        }) => i.base10_parse::<f64>(),
        // Allow `minimum = -5` etc. — negation parses as a unary expression.
        Expr::Unary(unary) => {
            if let syn::UnOp::Neg(_) = unary.op
                && let Expr::Lit(ExprLit { lit, .. }) = *unary.expr
            {
                let positive = match lit {
                    Lit::Float(f) => f.base10_parse::<f64>()?,
                    Lit::Int(i) => i.base10_parse::<f64>()?,
                    other => {
                        return Err(syn::Error::new_spanned(
                            other,
                            "expected a numeric literal after `-`",
                        ));
                    }
                };
                return Ok(-positive);
            }
            Err(syn::Error::new_spanned(unary, "expected a numeric literal"))
        }
        other => Err(syn::Error::new_spanned(
            other,
            "expected a numeric literal (int or float)",
        )),
    }
}

fn parse_str(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<String> {
    let lit: syn::LitStr = meta.value()?.parse()?;
    Ok(lit.value())
}

/// Parse a boolean attribute that may also appear as a bare keyword.
///
/// `#[schema(read_only)]`         → `true`
/// `#[schema(read_only = true)]`  → `true`
/// `#[schema(read_only = false)]` → `false`
fn parse_bool_or_default_true(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<bool> {
    // Try to parse a value; if there is no `=` after the key, fall back to
    // `true` (bare-keyword form).
    let Ok(value) = meta.value() else {
        return Ok(true);
    };
    let lit: syn::LitBool = value.parse()?;
    Ok(lit.value)
}

/// Parse an `example = ...` value into a `serde_json::Value`.
///
/// Accepts string / integer / float / boolean literals, and `null`.  More
/// complex shapes (objects, arrays) are not supported in attribute form —
/// users wanting structured examples should populate `example` programmatically
/// or via `#[schema(default = "...")]` which is already handled elsewhere.
fn parse_example_value(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<serde_json::Value> {
    let value = meta.value()?;
    let expr: Expr = value.parse()?;
    expr_to_json_value(&expr)
}

fn expr_to_json_value(expr: &Expr) -> syn::Result<serde_json::Value> {
    match expr {
        Expr::Lit(ExprLit { lit, .. }) => lit_to_json_value(lit),
        Expr::Unary(unary) => {
            if let syn::UnOp::Neg(_) = unary.op
                && let Expr::Lit(ExprLit { lit, .. }) = unary.expr.as_ref()
            {
                let positive = lit_to_json_value(lit)?;
                // Try integer first so that `example = -5` round-trips
                // as `serde_json::json!(-5)` (i64) and not as the
                // semantically equal but type-distinct `-5.0` (f64).
                if let Some(i) = positive.as_i64() {
                    return Ok(serde_json::json!(-i));
                }
                if let Some(n) = positive.as_f64() {
                    return Ok(serde_json::json!(-n));
                }
            }
            Err(syn::Error::new_spanned(
                expr,
                "expected a literal after `-`",
            ))
        }
        Expr::Path(path) if path.path.is_ident("null") => Ok(serde_json::Value::Null),
        other => Err(syn::Error::new_spanned(
            other,
            "expected a literal value (string / int / float / bool / null)",
        )),
    }
}

fn lit_to_json_value(lit: &Lit) -> syn::Result<serde_json::Value> {
    match lit {
        Lit::Str(s) => Ok(serde_json::Value::String(s.value())),
        Lit::Bool(b) => Ok(serde_json::Value::Bool(b.value)),
        Lit::Int(i) => Ok(serde_json::json!(i.base10_parse::<i64>()?)),
        Lit::Float(f) => Ok(serde_json::json!(f.base10_parse::<f64>()?)),
        other => Err(syn::Error::new_spanned(
            other,
            "unsupported literal type for `example`",
        )),
    }
}

// ── tests ────────────────────────────────────────────────────────────

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

    fn parse(attrs: &[Attribute]) -> SchemaConstraints {
        try_extract_schema_constraints(attrs).expect("schema attrs parse")
    }

    fn parse_err(attrs: &[Attribute]) -> syn::Error {
        try_extract_schema_constraints(attrs).expect_err("schema attrs must fail")
    }

    #[test]
    fn empty_attrs_produce_empty_constraints() {
        let c = parse(&[]);
        assert!(c.is_empty());
        assert!(!c.has_runtime_rule());
    }

    #[test]
    fn unrelated_attrs_are_ignored() {
        let c = parse(&[parse_quote!(#[serde(rename = "x")])]);
        assert!(c.is_empty());
    }

    #[test]
    fn struct_level_keys_are_ignored() {
        // `name`, `ref`, `nullable`, `default` are handled by other parsers;
        // this parser must walk the same `#[schema(...)]` attribute without
        // tripping on them.
        let c = parse(&[parse_quote!(#[schema(name = "Foo", nullable)])]);
        assert!(c.is_empty());
    }

    #[test]
    fn min_max_length_int_literals() {
        let c = parse(&[parse_quote!(#[schema(min_length = 3, max_length = 64)])]);
        assert_eq!(c.min_length, Some(3));
        assert_eq!(c.max_length, Some(64));
        assert!(c.has_runtime_rule());
    }

    #[test]
    fn pattern_str_literal() {
        let c = parse(&[parse_quote!(#[schema(pattern = "^[a-z]+$")])]);
        assert_eq!(c.pattern.as_deref(), Some("^[a-z]+$"));
    }

    #[test]
    fn minimum_maximum_accept_both_int_and_float() {
        let c1 = parse(&[parse_quote!(#[schema(minimum = 0, maximum = 150)])]);
        assert_eq!(c1.minimum, Some(0.0));
        assert_eq!(c1.maximum, Some(150.0));
        let c2 = parse(&[parse_quote!(#[schema(minimum = 0.5, maximum = 99.9)])]);
        assert_eq!(c2.minimum, Some(0.5));
        assert_eq!(c2.maximum, Some(99.9));
    }

    #[test]
    fn negative_minimum() {
        let c = parse(&[parse_quote!(#[schema(minimum = -10)])]);
        assert_eq!(c.minimum, Some(-10.0));
    }

    #[test]
    fn exclusive_bounds_default_to_true_when_bare() {
        let c = parse(&[parse_quote!(#[schema(exclusive_minimum, exclusive_maximum)])]);
        assert_eq!(c.exclusive_minimum, Some(true));
        assert_eq!(c.exclusive_maximum, Some(true));
    }

    #[test]
    fn exclusive_bounds_explicit_false() {
        let c = parse(&[parse_quote!(#[schema(exclusive_minimum = false)])]);
        assert_eq!(c.exclusive_minimum, Some(false));
    }

    #[test]
    fn multiple_of_float() {
        let c = parse(&[parse_quote!(#[schema(multiple_of = 0.25)])]);
        assert_eq!(c.multiple_of, Some(0.25));
    }

    #[test]
    fn min_max_items_with_unique() {
        let c = parse(&[parse_quote!(#[schema(min_items = 1, max_items = 5, unique_items)])]);
        assert_eq!(c.min_items, Some(1));
        assert_eq!(c.max_items, Some(5));
        assert_eq!(c.unique_items, Some(true));
    }

    #[test]
    fn format_strings() {
        let c = parse(&[parse_quote!(#[schema(format = "email")])]);
        assert_eq!(c.format.as_deref(), Some("email"));
        assert!(c.has_runtime_rule());

        let c2 = parse(&[parse_quote!(#[schema(format = "uuid")])]);
        // uuid has no garde rule — annotation only, no runtime rule.
        assert!(!c2.has_runtime_rule());
    }

    #[test]
    fn example_with_various_literal_kinds() {
        let c = parse(&[parse_quote!(#[schema(example = "hello")])]);
        assert_eq!(c.example, Some(serde_json::json!("hello")));

        let c = parse(&[parse_quote!(#[schema(example = 42)])]);
        assert_eq!(c.example, Some(serde_json::json!(42)));

        let c = parse(&[parse_quote!(#[schema(example = 2.5)])]);
        assert_eq!(c.example, Some(serde_json::json!(2.5)));

        let c = parse(&[parse_quote!(#[schema(example = true)])]);
        assert_eq!(c.example, Some(serde_json::json!(true)));

        let c = parse(&[parse_quote!(#[schema(example = -5)])]);
        assert_eq!(c.example, Some(serde_json::json!(-5)));
    }

    #[test]
    fn read_only_write_only_bare_and_explicit() {
        let c = parse(&[parse_quote!(#[schema(read_only, write_only = false)])]);
        assert_eq!(c.read_only, Some(true));
        assert_eq!(c.write_only, Some(false));
    }

    #[test]
    fn dive_bare_keyword_defaults_to_true() {
        let c = parse(&[parse_quote!(#[schema(dive)])]);
        assert_eq!(c.dive, Some(true));
        assert!(c.has_runtime_rule(), "dive should count as a runtime rule");
    }

    #[test]
    fn dive_explicit_false_disables_runtime_rule() {
        let c = parse(&[parse_quote!(#[schema(dive = false)])]);
        assert_eq!(c.dive, Some(false));
        assert!(
            !c.has_runtime_rule(),
            "dive = false must not register a runtime rule"
        );
    }

    #[test]
    fn dive_combines_with_other_constraints() {
        let c = parse(&[parse_quote!(#[schema(min_items = 1, max_items = 10, dive)])]);
        assert_eq!(c.min_items, Some(1));
        assert_eq!(c.max_items, Some(10));
        assert_eq!(c.dive, Some(true));
    }

    #[test]
    fn mixed_struct_and_field_keys_in_one_attr_are_partitioned_correctly() {
        // A user might write a single `#[schema(name = "...", min_length = 3)]`.
        // The struct-level `name` is ignored here; the field-level
        // `min_length` is parsed.
        let c = parse(&[parse_quote!(#[schema(name = "MyType", min_length = 3)])]);
        assert!(c.name_unaffected());
        assert_eq!(c.min_length, Some(3));
    }

    #[test]
    fn multiple_schema_attrs_accumulate() {
        let attrs: [Attribute; 2] = [
            parse_quote!(#[schema(min_length = 3)]),
            parse_quote!(#[schema(max_length = 32, format = "email")]),
        ];
        let c = parse(&attrs);
        assert_eq!(c.min_length, Some(3));
        assert_eq!(c.max_length, Some(32));
        assert_eq!(c.format.as_deref(), Some("email"));
    }

    impl SchemaConstraints {
        // helper for the partitioning test above — kept private to the
        // tests module so it doesn't pollute the public surface.
        fn name_unaffected(&self) -> bool {
            self.format.is_none() && self.example.is_none() && self.read_only.is_none()
        }
    }

    // ── extra coverage tests ─────────────────────────────────────────

    #[test]
    fn negative_float_minimum() {
        // Exercises the `Lit::Float` arm inside parse_f64's unary-minus
        // branch (not the Int arm that `negative_minimum` covers).
        let c = parse(&[parse_quote!(#[schema(minimum = -0.5)])]);
        assert_eq!(c.minimum, Some(-0.5));
    }

    #[test]
    fn example_negative_float_round_trips_as_f64() {
        // Negative float literal must serialize as a JSON number with
        // a fractional component — covers the `positive.as_f64()`
        // branch inside expr_to_json_value (the i64 fast path above
        // it is exercised separately by `example_with_various_...`).
        let c = parse(&[parse_quote!(#[schema(example = -2.5)])]);
        assert_eq!(c.example, Some(serde_json::json!(-2.5)));
    }

    #[test]
    fn example_null_literal_yields_json_null() {
        let c = parse(&[parse_quote!(#[schema(example = null)])]);
        assert_eq!(c.example, Some(serde_json::Value::Null));
    }

    #[test]
    fn negative_non_literal_minimum_is_rejected() {
        let err = parse_err(&[parse_quote!(#[schema(minimum = -CONST)])]);
        assert!(err.to_string().contains("expected a numeric literal"));
    }

    #[test]
    fn non_unary_non_lit_minimum_expr_is_rejected() {
        let err = parse_err(&[parse_quote!(#[schema(minimum = foo())])]);
        assert!(err.to_string().contains("expected a numeric literal"));
    }

    #[test]
    fn non_neg_unary_minimum_expr_is_rejected() {
        let err = parse_err(&[parse_quote!(#[schema(minimum = !5)])]);
        assert!(err.to_string().contains("expected a numeric literal"));
    }

    #[test]
    fn negative_non_numeric_literal_minimum_is_rejected() {
        let c1 = parse_err(&[parse_quote!(#[schema(minimum = -true)])]);
        assert!(c1.to_string().contains("expected a numeric literal"));
        let c2 = parse_err(&[parse_quote!(#[schema(minimum = -"x")])]);
        assert!(c2.to_string().contains("expected a numeric literal"));
    }

    #[test]
    fn example_negative_non_lit_is_rejected() {
        let err = parse_err(&[parse_quote!(#[schema(example = -CONST)])]);
        assert!(err.to_string().contains("expected a literal"));
    }

    #[test]
    fn example_non_lit_non_path_is_rejected() {
        let err = parse_err(&[parse_quote!(#[schema(example = some_fn())])]);
        assert!(err.to_string().contains("expected a literal value"));
    }

    #[test]
    fn example_byte_string_literal_is_rejected() {
        let err = parse_err(&[parse_quote!(#[schema(example = b"bytes")])]);
        assert!(err.to_string().contains("unsupported literal type"));
    }

    #[test]
    fn unknown_key_with_value_is_consumed_without_error() {
        // The `else { ... }` branch inside `parse_nested_meta` must
        // consume any `= value` payload of an unrecognised key so
        // sibling keys still parse.  Pair an unknown key WITH a
        // recognised one to confirm the latter still lands.
        let c = parse(&[parse_quote!(#[schema(unknown_key = "value", min_length = 3)])]);
        assert_eq!(c.min_length, Some(3));
    }

    #[test]
    fn bare_unknown_key_does_not_panic() {
        // Bare keyword form of an unknown key — `meta.value()` will
        // return Err, the `if let Ok(value)` falls through, and
        // parse_nested_meta moves on.
        let c = parse(&[parse_quote!(#[schema(unknown_bare_kw, min_length = 3)])]);
        assert_eq!(c.min_length, Some(3));
    }

    // ── `any` flag tests ────────────────────────────────────────────

    #[test]
    fn bare_any_defaults_to_true() {
        let c = parse(&[parse_quote!(#[schema(any)])]);
        assert_eq!(c.any, Some(true));
        assert!(c.is_any());
        // `any` is NOT a runtime rule — it's a schema-shape override.
        assert!(!c.has_runtime_rule());
    }

    #[test]
    fn any_explicit_false_disables_override() {
        let c = parse(&[parse_quote!(#[schema(any = false)])]);
        assert_eq!(c.any, Some(false));
        assert!(!c.is_any());
    }

    #[test]
    fn any_combines_with_other_constraints() {
        // `any` overrides the schema to object, but a user might still
        // ask for OpenAPI documentation annotations to ride along.
        let c = parse(&[parse_quote!(#[schema(any, read_only)])]);
        assert_eq!(c.any, Some(true));
        assert_eq!(c.read_only, Some(true));
    }

    #[test]
    fn is_empty_accounts_for_any() {
        let c = parse(&[parse_quote!(#[schema(any)])]);
        assert!(
            !c.is_empty(),
            "a field carrying only `#[schema(any)]` must not be reported empty"
        );
    }

    #[rstest::rstest]
    #[case("uri")]
    #[case("url")]
    #[case("ipv4")]
    #[case("ipv6")]
    #[case("ip")]
    fn garde_formats_are_runtime_rules(#[case] format: &str) {
        let item: syn::ItemStruct =
            syn::parse_str(&format!(r#"#[schema(format = "{format}")] struct Value;"#)).unwrap();
        assert!(parse(&item.attrs).has_runtime_rule());
    }
}