clapfig 0.21.5-rc.2

Rich, layered configuration for Rust CLI apps
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
//! Static-form, const-friendly schema types — the emission target of the
//! `#[derive(clapfig::Schema)]` proc macro.
//!
//! The runtime-side [`Schema`](crate::runtime::Schema) holds owned
//! `String` / `Vec` / `toml::Value` data. That shape is convenient for a
//! builder-built schema but unfit for a `const SCHEMA: ... = ...` form, so
//! the macro emits a parallel tree whose every field is `&'static`. At
//! first call, [`Schema::schema`] caches a converted
//! `runtime::Schema` in a per-type `OnceLock`; all existing schema
//! consumers walk the cached runtime view.
//!
//! This file is the single source of truth for that mirror.

use std::sync::{Arc, OnceLock};

use crate::runtime::{
    Field as RuntimeField, Leaf as RuntimeLeaf, LeafType as RuntimeLeafType,
    NamedField as RuntimeNamedField, Schema as RuntimeSchema,
};
use toml::Value as TomlValue;

/// `const`-friendly mirror of [`runtime::Schema`](crate::runtime::Schema).
///
/// The macro emits one of these per struct (and one per nested struct).
/// Convert to the runtime form via [`SchemaStatic::to_runtime`] or read
/// the cached runtime view via [`Schema::schema`].
///
/// Unit-only enums also derive [`Schema`] (so a field of that type can
/// compose via the same `<T as Schema>::STATIC` reference the macro uses
/// for nested structs). For an enum the `fields` slice is empty and
/// `enum_variants` carries the variant names (post-`rename_all` /
/// per-variant `rename`). The converter inspects `enum_variants` when
/// flattening a `FieldStatic::Nested(...)`: a non-empty list becomes a
/// `Field::Leaf` with `LeafType::Enum`, while an empty list keeps the
/// nested-object shape.
#[derive(Debug)]
pub struct SchemaStatic {
    pub name: &'static str,
    pub doc: &'static [&'static str],
    pub strict: Option<bool>,
    pub fields: &'static [NamedFieldStatic],
    /// For unit-only enum types: variant names (post-rename). For struct
    /// schemas this slice is empty.
    pub enum_variants: &'static [&'static str],
}

/// `const`-friendly mirror of [`runtime::NamedField`](crate::runtime::NamedField).
#[derive(Debug)]
pub struct NamedFieldStatic {
    pub name: &'static str,
    pub field: FieldStatic,
}

/// `const`-friendly mirror of [`runtime::Field`](crate::runtime::Field).
#[derive(Debug)]
pub enum FieldStatic {
    Leaf(LeafStatic),
    Nested(&'static SchemaStatic),
    ArrayOf(&'static SchemaStatic),
    /// Maps of nested objects (TOML `[name.<key>]`). Emitted by the
    /// derive macro for `HashMap<String, NestedStruct>` /
    /// `BTreeMap<String, NestedStruct>` fields where the value type
    /// derives [`Schema`](crate::Schema).
    MapOf(&'static SchemaStatic),
}

/// `const`-friendly mirror of [`runtime::Leaf`](crate::runtime::Leaf).
#[derive(Debug)]
pub struct LeafStatic {
    pub doc: &'static [&'static str],
    pub ty: LeafTypeStatic,
    pub default: Option<ValueStatic>,
    pub optional: bool,
    pub env: Option<&'static str>,
}

/// `const`-friendly mirror of [`runtime::LeafType`](crate::runtime::LeafType).
#[derive(Debug)]
pub enum LeafTypeStatic {
    String,
    /// Signed 64-bit integer (TOML's only integer width).
    ///
    /// The derive macro maps every Rust integer type, including the
    /// unsigned ones (`u8`/`u16`/`u32`/`u64`/`usize`) and `isize`, to
    /// this variant. Values that exceed `i64::MAX` (e.g. a `u64`
    /// holding 2^63) **cannot be represented in TOML at all** — the
    /// failure mode is at serialize time, before the value ever
    /// reaches a deserializer, and there is no faithful intermediate.
    /// Field types like `u64` are accepted because they are convenient
    /// and round-trip correctly for the overwhelming majority of
    /// values; callers who need the full unsigned-64 range should
    /// store them as `String` and parse explicitly.
    ///
    /// `i128` and `u128` are rejected at derive time with a compile
    /// error rather than silently truncated.
    Integer,
    Float,
    Bool,
    DateTime,
    Array(&'static LeafTypeStatic),
    Map(&'static LeafTypeStatic),
    Enum {
        values: &'static [ValueStatic],
    },
    /// Defer the enum variant set to a referenced `SchemaStatic`.
    ///
    /// Emitted by the derive macro in two scenarios that the runtime
    /// representation can't tell apart syntactically:
    ///
    /// - **Leaf attrs on a nested-typed field** —
    ///   `#[clapfig(default = "letter")] page_size: PdfPageSize`. The
    ///   macro sees `Nested` and the leaf attrs together and routes
    ///   through `EnumRef`.
    /// - **`Option<Nested>` wrapping** — `page_size: Option<Mode>` (or
    ///   `Option<DbStruct>`). The macro can't tell `Mode` (unit enum)
    ///   from `DbStruct` (struct) at the field site; both classify as
    ///   `Optional(Nested(_))`. Routing through `EnumRef` lets
    ///   `Option<UnitEnum>` work; `Option<NestedStruct>` falls through
    ///   to the deferred-kind check.
    ///
    /// `field_name` is the parent struct's field name (post any
    /// `#[clapfig(rename = ...)]`); the converter uses it inside the
    /// authoring-error panic message so the user can locate the
    /// offending field without grepping. Same deferred-error pattern
    /// as the datetime-default literal parsing.
    EnumRef {
        schema: &'static SchemaStatic,
        field_name: &'static str,
    },
    Value,
}

/// `const`-friendly mirror of `toml::Value` for default-value emission.
///
/// Datetimes are stored as their string form and parsed on conversion,
/// since `toml::value::Datetime` is not `const`-constructible.
#[derive(Debug)]
pub enum ValueStatic {
    String(&'static str),
    Integer(i64),
    Float(f64),
    Bool(bool),
    Datetime(&'static str),
    Array(&'static [ValueStatic]),
    Table(&'static [(&'static str, ValueStatic)]),
}

impl SchemaStatic {
    pub fn to_runtime(&self) -> RuntimeSchema {
        RuntimeSchema {
            name: self.name.to_string(),
            doc: self.doc.iter().map(|s| (*s).to_string()).collect(),
            strict: self.strict,
            fields: self
                .fields
                .iter()
                .map(NamedFieldStatic::to_runtime)
                .collect(),
        }
    }

    /// `true` when this schema represents a unit-only enum rather than a
    /// struct. The macro emits an empty `fields` slice for enums and
    /// populates `enum_variants` instead; the converter consults this
    /// when flattening a `FieldStatic::Nested(...)` into the runtime form.
    pub fn is_enum(&self) -> bool {
        !self.enum_variants.is_empty()
    }
}

impl NamedFieldStatic {
    fn to_runtime(&self) -> RuntimeNamedField {
        RuntimeNamedField {
            name: self.name.to_string(),
            field: self.field.to_runtime(),
        }
    }
}

impl FieldStatic {
    fn to_runtime(&self) -> RuntimeField {
        match self {
            FieldStatic::Leaf(leaf) => RuntimeField::Leaf(leaf.to_runtime()),
            // Flatten an enum-kind nested schema (a unit-only enum that
            // derived `Schema`) into a runtime leaf carrying the variant
            // list. The macro can't tell at parse time whether a field's
            // type is a struct or an enum — so it always emits
            // `FieldStatic::Nested(<T as Schema>::STATIC)`, and the kind
            // distinction happens here.
            FieldStatic::Nested(s) if s.is_enum() => RuntimeField::Leaf(RuntimeLeaf {
                doc: s.doc.iter().map(|d| (*d).to_string()).collect(),
                ty: RuntimeLeafType::Enum {
                    values: s
                        .enum_variants
                        .iter()
                        .map(|v| TomlValue::String((*v).to_string()))
                        .collect(),
                },
                default: None,
                optional: false,
                env: None,
            }),
            FieldStatic::Nested(s) => RuntimeField::Nested(s.to_runtime()),
            FieldStatic::ArrayOf(s) => RuntimeField::ArrayOf(s.to_runtime()),
            FieldStatic::MapOf(s) => RuntimeField::MapOf(s.to_runtime()),
        }
    }
}

impl LeafStatic {
    fn to_runtime(&self) -> RuntimeLeaf {
        RuntimeLeaf {
            doc: self.doc.iter().map(|s| (*s).to_string()).collect(),
            ty: self.ty.to_runtime(),
            default: self.default.as_ref().map(ValueStatic::to_toml),
            optional: self.optional,
            env: self.env.map(|s| s.to_string()),
        }
    }
}

impl LeafTypeStatic {
    pub fn to_runtime(&self) -> RuntimeLeafType {
        match self {
            LeafTypeStatic::String => RuntimeLeafType::String,
            LeafTypeStatic::Integer => RuntimeLeafType::Integer,
            LeafTypeStatic::Float => RuntimeLeafType::Float,
            LeafTypeStatic::Bool => RuntimeLeafType::Bool,
            LeafTypeStatic::DateTime => RuntimeLeafType::DateTime,
            LeafTypeStatic::Array(elem) => RuntimeLeafType::Array(Box::new(elem.to_runtime())),
            LeafTypeStatic::Map(v) => RuntimeLeafType::Map(Box::new(v.to_runtime())),
            LeafTypeStatic::Enum { values } => RuntimeLeafType::Enum {
                values: values.iter().map(ValueStatic::to_toml).collect(),
            },
            LeafTypeStatic::EnumRef { schema, field_name } => {
                // Deferred enum-kind check. The macro can't syntactically
                // distinguish a unit enum from a struct at the field
                // site, so two distinct authoring paths land here and
                // need separately-named remediations:
                //
                //   1. `#[clapfig(default = ...)] field: SomeStruct` —
                //      leaf attrs on a nested struct. Drop the attrs
                //      (struct fields are nested-section shaped).
                //   2. `field: Option<SomeStruct>` — `Option`-wrapped
                //      nested struct. Drop the `Option` wrapper (an
                //      absent nested section is already the empty-
                //      table state).
                //
                // Same first-`schema()`-call failure mode as a
                // malformed datetime default.
                assert!(
                    schema.is_enum(),
                    "clapfig: field `{field_name}` references type `{schema_name}` which is a \
                     struct, not a unit-only enum. The derive macro routed this field through \
                     `LeafTypeStatic::EnumRef` because either (a) it carries leaf attributes \
                     (`default` / `env` / `optional`) — drop the attributes; struct fields are \
                     nested-section shaped — or (b) the type is `Option<{schema_name}>` — drop \
                     the `Option` wrapper; an absent nested section is already the empty-table \
                     state. If `{schema_name}` is meant to be a unit-only enum, change its body \
                     to `enum {schema_name} {{ ... }}` with payload-free variants.",
                    schema_name = schema.name,
                );
                RuntimeLeafType::Enum {
                    values: schema
                        .enum_variants
                        .iter()
                        .map(|v| TomlValue::String((*v).to_string()))
                        .collect(),
                }
            }
            LeafTypeStatic::Value => RuntimeLeafType::Value,
        }
    }
}

impl ValueStatic {
    pub fn to_toml(&self) -> TomlValue {
        match self {
            ValueStatic::String(s) => TomlValue::String((*s).to_string()),
            ValueStatic::Integer(i) => TomlValue::Integer(*i),
            ValueStatic::Float(f) => TomlValue::Float(*f),
            ValueStatic::Bool(b) => TomlValue::Boolean(*b),
            ValueStatic::Datetime(s) => TomlValue::Datetime(
                s.parse()
                    .expect("clapfig: invalid datetime literal in static schema default"),
            ),
            ValueStatic::Array(items) => {
                TomlValue::Array(items.iter().map(ValueStatic::to_toml).collect())
            }
            ValueStatic::Table(entries) => {
                let mut t = toml::map::Map::new();
                for (k, v) in entries.iter() {
                    t.insert((*k).to_string(), v.to_toml());
                }
                TomlValue::Table(t)
            }
        }
    }
}

/// Marker trait implemented by structs deriving [`clapfig::Schema`](crate::Schema).
///
/// The macro emits a [`STATIC`](Schema::STATIC) associated const carrying
/// the const-form schema tree, plus a [`schema`](Schema::schema) accessor
/// that lazily converts and caches a runtime
/// [`Schema`](crate::runtime::Schema). The associated const lets nested
/// struct references (e.g. `<DbConfig as Schema>::STATIC`) appear inside
/// the parent's `static SchemaStatic = ...` initializer — fn-form trait
/// methods cannot, since trait fns are not callable in const contexts on
/// stable Rust.
///
/// Every existing schema consumer (JSON-Schema emission, template
/// generation, persistence validation, strictness cascade, etc.) walks
/// the cached runtime view, so static and runtime entry points produce
/// byte-identical behavior.
pub trait Schema {
    /// The macro-emitted const schema tree. Const so it composes inside
    /// nested `static SchemaStatic = ...` initializers.
    const STATIC: &'static SchemaStatic;

    /// Convenience accessor; equivalent to `Self::STATIC`.
    fn schema_static() -> &'static SchemaStatic {
        Self::STATIC
    }

    /// Cached runtime view. The macro emits this method explicitly with a
    /// per-impl `OnceLock`; the helper [`cached_runtime_schema`] keeps the
    /// generated body small.
    fn schema() -> &'static RuntimeSchema;

    /// `Arc`-flavored access to the same cached runtime view. Used by the
    /// macro-driven builder ([`crate::SchemaConfigBuilder`]) to avoid
    /// cloning the schema tree per builder construction — the runtime
    /// spec stores an `Arc<Schema>` and the cache hands out cheap
    /// reference-counted handles to it. Cost: one `Arc::clone` per call
    /// (atomic increment, no allocation).
    fn schema_arc() -> Arc<RuntimeSchema>;

    /// Flat list of every dotted path the schema knows about: leaf
    /// addressable keys plus every nested-section and array-of-objects
    /// node. Lets consumer code (extension registries, doc generators,
    /// `--list-keys` flags) replace hand-maintained "known paths"
    /// constants — the macro recomputes the list every time a field is
    /// added or removed.
    ///
    /// Ordering is depth-first, matching the order fields appear in the
    /// source struct (parents emit their own path before recursing into
    /// children). Array-of-objects nodes contribute the array name once
    /// (`"plugins"`); individual array entries are not addressable as
    /// distinct paths at this layer so no `plugins[N]` form is emitted.
    /// Unit-enum leaves contribute only their own path (the variant set
    /// is metadata on the leaf, not a separate sub-path).
    ///
    /// The default impl walks `Self::STATIC`. Override is rarely needed.
    fn field_paths() -> Vec<String> {
        let mut out = Vec::new();
        collect_field_paths(Self::STATIC, "", &mut out);
        out
    }
}

/// Depth-first walk of a [`SchemaStatic`] tree that appends each node's
/// dotted path to `out`. Backs [`Schema::field_paths`]; exposed publicly
/// because consumers that already have a `&SchemaStatic` (rare — usually
/// they have the trait impl instead) can reuse the same traversal.
///
/// `prefix` is the dotted path of the *current* schema's parent (or `""`
/// at the root). Each child appends its own name to the prefix; for a
/// leaf the appended path is added to `out`, and for a nested or
/// array-of subtree the section path is added *before* recursing so
/// downstream consumers can use the list as a section/path inventory in
/// one read.
pub fn collect_field_paths(schema: &SchemaStatic, prefix: &str, out: &mut Vec<String>) {
    for field in schema.fields {
        let dotted = if prefix.is_empty() {
            field.name.to_string()
        } else {
            format!("{prefix}.{}", field.name)
        };
        match &field.field {
            FieldStatic::Leaf(_) => out.push(dotted),
            FieldStatic::Nested(child) if child.is_enum() => {
                // Enum-kind nested schemas flatten to a `LeafType::Enum`
                // at the runtime layer; surface them here as a single
                // leaf path, not a section + variant paths.
                out.push(dotted);
            }
            FieldStatic::Nested(child)
            | FieldStatic::ArrayOf(child)
            | FieldStatic::MapOf(child) => {
                out.push(dotted.clone());
                collect_field_paths(child, &dotted, out);
            }
        }
    }
}

/// Shared helper invoked by macro-generated [`Schema::schema`] bodies.
///
/// The cache holds `Arc<Schema>` (not `Schema`) so [`Schema::schema_arc`]
/// can hand out cheap reference-counted clones without re-running
/// `to_runtime()`. [`Schema::schema`] returns a `&'static Schema` by
/// dereferencing through the `Arc` — the deref is sound because the
/// `OnceLock` itself is `'static`.
pub fn cached_runtime_schema(
    cell: &'static OnceLock<Arc<RuntimeSchema>>,
    static_schema: &'static SchemaStatic,
) -> &'static RuntimeSchema {
    let arc: &'static Arc<RuntimeSchema> =
        cell.get_or_init(|| Arc::new(static_schema.to_runtime()));
    arc.as_ref()
}

/// `Arc`-returning counterpart to [`cached_runtime_schema`].
pub fn cached_runtime_schema_arc(
    cell: &'static OnceLock<Arc<RuntimeSchema>>,
    static_schema: &'static SchemaStatic,
) -> Arc<RuntimeSchema> {
    cell.get_or_init(|| Arc::new(static_schema.to_runtime()))
        .clone()
}

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

    static EMPTY_DOC: &[&str] = &[];

    static MINIMAL_SCHEMA: SchemaStatic = SchemaStatic {
        name: "Minimal",
        doc: EMPTY_DOC,
        strict: None,
        fields: &[NamedFieldStatic {
            name: "port",
            field: FieldStatic::Leaf(LeafStatic {
                doc: EMPTY_DOC,
                ty: LeafTypeStatic::Integer,
                default: Some(ValueStatic::Integer(8080)),
                optional: false,
                env: None,
            }),
        }],
        enum_variants: &[],
    };

    #[test]
    fn static_to_runtime_roundtrips_minimal_shape() {
        let s = MINIMAL_SCHEMA.to_runtime();
        assert_eq!(s.name, "Minimal");
        assert_eq!(s.fields.len(), 1);
        match &s.fields[0].field {
            RuntimeField::Leaf(leaf) => {
                assert!(matches!(leaf.ty, RuntimeLeafType::Integer));
                assert_eq!(leaf.default, Some(TomlValue::Integer(8080)));
                assert!(!leaf.optional);
            }
            other => panic!("expected Leaf, got {other:?}"),
        }
    }

    #[test]
    fn value_static_array_to_toml_recurses() {
        let v = ValueStatic::Array(&[
            ValueStatic::String("a"),
            ValueStatic::String("b"),
            ValueStatic::Integer(1),
        ]);
        let toml = v.to_toml();
        match toml {
            TomlValue::Array(items) => {
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], TomlValue::String("a".into()));
                assert_eq!(items[2], TomlValue::Integer(1));
            }
            other => panic!("expected Array, got {other:?}"),
        }
    }

    #[test]
    fn value_static_table_to_toml_preserves_keys() {
        let v = ValueStatic::Table(&[
            ("name", ValueStatic::String("x")),
            ("count", ValueStatic::Integer(3)),
        ]);
        match v.to_toml() {
            TomlValue::Table(t) => {
                assert_eq!(t.get("name").unwrap().as_str(), Some("x"));
                assert_eq!(t.get("count").unwrap().as_integer(), Some(3));
            }
            other => panic!("expected Table, got {other:?}"),
        }
    }

    #[test]
    fn leaf_type_static_enum_to_runtime_carries_values() {
        let lt = LeafTypeStatic::Enum {
            values: &[
                ValueStatic::String("debug"),
                ValueStatic::String("info"),
                ValueStatic::String("warn"),
                ValueStatic::String("error"),
            ],
        };
        match lt.to_runtime() {
            RuntimeLeafType::Enum { values } => {
                assert_eq!(values.len(), 4);
                assert_eq!(values[0], TomlValue::String("debug".into()));
            }
            other => panic!("expected Enum, got {other:?}"),
        }
    }

    static NESTED_INNER: SchemaStatic = SchemaStatic {
        name: "Inner",
        doc: EMPTY_DOC,
        strict: None,
        fields: &[NamedFieldStatic {
            name: "url",
            field: FieldStatic::Leaf(LeafStatic {
                doc: EMPTY_DOC,
                ty: LeafTypeStatic::String,
                default: None,
                optional: true,
                env: None,
            }),
        }],
        enum_variants: &[],
    };

    static NESTED_OUTER: SchemaStatic = SchemaStatic {
        name: "Outer",
        doc: EMPTY_DOC,
        strict: None,
        fields: &[NamedFieldStatic {
            name: "db",
            field: FieldStatic::Nested(&NESTED_INNER),
        }],
        enum_variants: &[],
    };

    static ENUM_PDF_PAGE: SchemaStatic = SchemaStatic {
        name: "PdfPageSize",
        doc: EMPTY_DOC,
        strict: None,
        fields: &[],
        enum_variants: &["a4", "letter"],
    };

    static ENUM_CONTAINER: SchemaStatic = SchemaStatic {
        name: "Doc",
        doc: EMPTY_DOC,
        strict: None,
        fields: &[NamedFieldStatic {
            name: "page_size",
            field: FieldStatic::Nested(&ENUM_PDF_PAGE),
        }],
        enum_variants: &[],
    };

    #[test]
    fn enum_kind_static_flattens_to_runtime_leaf_enum() {
        let s = ENUM_CONTAINER.to_runtime();
        assert_eq!(s.fields.len(), 1);
        match &s.fields[0].field {
            RuntimeField::Leaf(leaf) => match &leaf.ty {
                RuntimeLeafType::Enum { values } => {
                    assert_eq!(values.len(), 2);
                    assert_eq!(values[0], TomlValue::String("a4".into()));
                    assert_eq!(values[1], TomlValue::String("letter".into()));
                }
                other => panic!("expected Enum, got {other:?}"),
            },
            other => panic!("expected Leaf (enum flattened), got {other:?}"),
        }
    }

    #[test]
    fn is_enum_distinguishes_struct_from_enum_schema() {
        assert!(!MINIMAL_SCHEMA.is_enum());
        assert!(ENUM_PDF_PAGE.is_enum());
    }

    #[test]
    fn nested_static_schemas_compose_via_static_reference() {
        let s = NESTED_OUTER.to_runtime();
        assert_eq!(s.fields.len(), 1);
        match &s.fields[0].field {
            RuntimeField::Nested(inner) => {
                assert_eq!(inner.name, "Inner");
                assert_eq!(inner.fields.len(), 1);
            }
            other => panic!("expected Nested, got {other:?}"),
        }
    }

    #[test]
    fn cached_runtime_schema_returns_same_pointer_across_calls() {
        static CELL: OnceLock<Arc<RuntimeSchema>> = OnceLock::new();
        let a = cached_runtime_schema(&CELL, &MINIMAL_SCHEMA);
        let b = cached_runtime_schema(&CELL, &MINIMAL_SCHEMA);
        assert!(std::ptr::eq(a, b));
    }

    #[test]
    fn cached_runtime_schema_arc_shares_underlying_schema_with_ref_accessor() {
        static CELL: OnceLock<Arc<RuntimeSchema>> = OnceLock::new();
        let r = cached_runtime_schema(&CELL, &MINIMAL_SCHEMA);
        let a = cached_runtime_schema_arc(&CELL, &MINIMAL_SCHEMA);
        // Both accessors must yield the same in-memory schema — pointer
        // equality after deref through the Arc.
        assert!(std::ptr::eq(r, a.as_ref()));
    }
}