eure-schema 0.1.8

Schema specification and validation for Eure
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
//! Schema building from Rust types
//!
//! This module provides the [`BuildSchema`] trait and [`SchemaBuilder`] for
//! generating schema definitions from Rust types, either manually or via derive.
//!
//! # Example
//!
//! ```ignore
//! use eure_schema::{BuildSchema, SchemaDocument};
//!
//! #[derive(BuildSchema)]
//! #[eure(type_name = "user")]
//! struct User {
//!     name: String,
//!     age: Option<u32>,
//! }
//!
//! let schema = SchemaDocument::of::<User>();
//! ```

use std::any::TypeId;
use std::collections::HashMap;

use eure_document::Text;
use eure_document::identifier::Identifier;
use indexmap::IndexMap;

use crate::{
    CodegenDefaults, ExtTypeSchema, RootCodegen, SchemaDocument, SchemaMetadata, SchemaNode,
    SchemaNodeContent, SchemaNodeId, TextSchema, TypeCodegen,
};

/// Trait for types that can build their schema representation.
///
/// This trait is typically derived using `#[derive(BuildSchema)]`, but can also
/// be implemented manually for custom schema generation.
///
/// # Type Registration
///
/// Types can optionally provide a `type_name()` to register themselves in the
/// schema's `$types` namespace. This is useful for:
/// - Creating reusable type definitions
/// - Enabling type references across the schema
/// - Providing meaningful names in generated schemas
///
/// Primitive types typically return `None` for `type_name()`.
/// Full node specification returned by [`BuildSchema::build_schema_node`].
///
/// Mirrors [`SchemaNode`] but is used during schema construction to allow
/// types to specify all node-level properties including `ext_types` and
/// `type_codegen`, which cannot be expressed through `build_schema` alone.
pub struct SchemaNodeSpec {
    pub content: SchemaNodeContent,
    pub metadata: SchemaMetadata,
    pub ext_types: IndexMap<Identifier, ExtTypeSchema>,
    pub type_codegen: TypeCodegen,
}

pub trait BuildSchema {
    /// The type name for registration in `$types` namespace.
    ///
    /// Return `Some("my-type")` to register this type as `$types.my-type`.
    /// Return `None` (default) for inline/anonymous types.
    fn type_name() -> Option<&'static str> {
        None
    }

    /// Build the schema content for this type.
    ///
    /// Use `ctx.build::<T>()` for nested types - this handles caching
    /// and recursion automatically.
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent;

    /// Optional metadata for this type's schema node.
    ///
    /// Override to provide description, deprecation status, defaults, or examples.
    fn schema_metadata() -> SchemaMetadata {
        SchemaMetadata::default()
    }

    /// Build the full node specification for this type.
    ///
    /// Override this method to set `ext_types` or `type_codegen` on the node.
    /// The default implementation delegates to `build_schema` and `schema_metadata`.
    fn build_schema_node(ctx: &mut SchemaBuilder) -> SchemaNodeSpec {
        SchemaNodeSpec {
            content: Self::build_schema(ctx),
            metadata: Self::schema_metadata(),
            ext_types: IndexMap::new(),
            type_codegen: TypeCodegen::None,
        }
    }
}

/// Builder for constructing schema documents from Rust types.
///
/// The builder maintains:
/// - An arena of schema nodes
/// - A cache by `TypeId` to prevent duplicate definitions and handle recursion
/// - Type registrations for the `$types` namespace
pub struct SchemaBuilder {
    /// The schema document being built
    doc: SchemaDocument,
    /// Cache of built types by TypeId (prevents duplicates, handles recursion)
    cache: HashMap<TypeId, SchemaNodeId>,
}

impl SchemaBuilder {
    /// Create a new schema builder.
    pub fn new() -> Self {
        Self {
            doc: SchemaDocument {
                nodes: Vec::new(),
                root: SchemaNodeId(0), // Will be set in finish()
                types: Default::default(),
                root_codegen: RootCodegen::default(),
                codegen_defaults: CodegenDefaults::default(),
            },
            cache: HashMap::new(),
        }
    }

    /// Build the schema for type `T`, with caching and recursion handling.
    ///
    /// This is the primary method for building nested types. It:
    /// 1. Returns cached ID if already built (idempotent)
    /// 2. Reserves a node slot before building (handles recursion)
    /// 3. Calls `T::build_schema_node()` to get the full node spec
    /// 4. For named types: registers in $types and returns a Reference node
    pub fn build<T: BuildSchema + 'static>(&mut self) -> SchemaNodeId {
        let type_id = TypeId::of::<T>();

        // Return cached if already built
        if let Some(&id) = self.cache.get(&type_id) {
            return id;
        }

        // Check if this type has a name (for registration)
        let type_name = T::type_name();

        // For named types, we need two nodes: content + reference
        // For unnamed types, just the content node
        if let Some(name) = type_name {
            // Reserve a slot for the content node
            let content_id = self.reserve_node();

            // Build the full node spec
            let spec = T::build_schema_node(self);
            self.set_node_spec(content_id, spec);

            // Register the type
            if let Ok(ident) = name.parse::<eure_document::identifier::Identifier>() {
                self.doc.types.insert(ident, content_id);
            }

            // Create a Reference node that points to this type
            let ref_id = self.create_node(SchemaNodeContent::Reference(crate::TypeReference {
                namespace: None,
                name: name.parse().expect("valid type name"),
            }));

            // Cache the reference ID so subsequent calls return the reference
            self.cache.insert(type_id, ref_id);
            ref_id
        } else {
            // Unnamed type: just build and cache the content node
            let id = self.reserve_node();
            self.cache.insert(type_id, id);

            let spec = T::build_schema_node(self);
            self.set_node_spec(id, spec);

            id
        }
    }

    /// Create a schema node with the given content.
    ///
    /// Use this for creating anonymous/inline nodes that don't need caching.
    /// For types that implement `BuildSchema`, prefer `build::<T>()`.
    pub fn create_node(&mut self, content: SchemaNodeContent) -> SchemaNodeId {
        let id = SchemaNodeId(self.doc.nodes.len());
        self.doc.nodes.push(SchemaNode {
            content,
            metadata: SchemaMetadata::default(),
            ext_types: Default::default(),
            type_codegen: TypeCodegen::None,
        });
        id
    }

    /// Create a schema node with content and metadata.
    pub fn create_node_with_metadata(
        &mut self,
        content: SchemaNodeContent,
        metadata: SchemaMetadata,
    ) -> SchemaNodeId {
        let id = SchemaNodeId(self.doc.nodes.len());
        self.doc.nodes.push(SchemaNode {
            content,
            metadata,
            ext_types: Default::default(),
            type_codegen: TypeCodegen::None,
        });
        id
    }

    /// Reserve a node slot, returning its ID.
    ///
    /// The node is initialized with `Any` content and must be finalized
    /// with `set_node()` before the schema is complete.
    fn reserve_node(&mut self) -> SchemaNodeId {
        let id = SchemaNodeId(self.doc.nodes.len());
        self.doc.nodes.push(SchemaNode {
            content: SchemaNodeContent::Any, // Placeholder
            metadata: SchemaMetadata::default(),
            ext_types: Default::default(),
            type_codegen: TypeCodegen::None,
        });
        id
    }

    /// Apply a full [`SchemaNodeSpec`] to a reserved node.
    fn set_node_spec(&mut self, id: SchemaNodeId, spec: SchemaNodeSpec) {
        let node = &mut self.doc.nodes[id.0];
        node.content = spec.content;
        node.metadata = spec.metadata;
        node.ext_types = spec.ext_types;
        node.type_codegen = spec.type_codegen;
    }

    /// Get mutable access to a node for adding ext_types or modifying metadata.
    pub fn node_mut(&mut self, id: SchemaNodeId) -> &mut SchemaNode {
        &mut self.doc.nodes[id.0]
    }

    /// Register a named type in the `$types` namespace.
    pub fn register_type(&mut self, name: &str, id: SchemaNodeId) {
        if let Ok(ident) = name.parse() {
            self.doc.types.insert(ident, id);
        }
    }

    /// Consume the builder and produce the final schema document.
    pub fn finish(mut self, root: SchemaNodeId) -> SchemaDocument {
        self.doc.root = root;
        self.doc
    }
}

impl Default for SchemaBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl SchemaDocument {
    /// Generate a schema document for type `T`.
    ///
    /// This is the main entry point for schema generation from Rust types.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use eure_schema::SchemaDocument;
    ///
    /// let schema = SchemaDocument::of::<MyType>();
    /// ```
    pub fn of<T: BuildSchema + 'static>() -> SchemaDocument {
        let mut builder = SchemaBuilder::new();
        let root = builder.build::<T>();
        builder.finish(root)
    }
}

// ============================================================================
// Primitive Type Implementations
// ============================================================================

impl BuildSchema for String {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Text(crate::TextSchema::default())
    }
}

impl BuildSchema for &str {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Text(crate::TextSchema::default())
    }
}

impl BuildSchema for bool {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Boolean
    }
}

macro_rules! impl_build_schema_int {
    ($($ty:ty),*) => {
        $(
            impl BuildSchema for $ty {
                fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
                    SchemaNodeContent::Integer(crate::IntegerSchema::default())
                }
            }
        )*
    };
}

impl_build_schema_int!(
    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
);

// Floats
impl BuildSchema for f32 {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Float(crate::FloatSchema {
            precision: crate::FloatPrecision::F32,
            ..Default::default()
        })
    }
}

impl BuildSchema for f64 {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Float(crate::FloatSchema {
            precision: crate::FloatPrecision::F64,
            ..Default::default()
        })
    }
}

// Unit type
impl BuildSchema for () {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Null
    }
}

impl BuildSchema for Text {
    fn build_schema(_ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        SchemaNodeContent::Text(TextSchema {
            language: None,
            min_length: None,
            max_length: None,
            pattern: None,
            unknown_fields: IndexMap::new(),
        })
    }
}

// ============================================================================
// Compound Type Implementations
// ============================================================================

/// Option<T> is represented as a union: some(T) | none(null)
impl<T: BuildSchema + 'static> BuildSchema for Option<T> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let some_schema = ctx.build::<T>();
        let none_schema = ctx.create_node(SchemaNodeContent::Null);

        SchemaNodeContent::Union(crate::UnionSchema {
            variants: IndexMap::from([
                ("some".to_string(), some_schema),
                ("none".to_string(), none_schema),
            ]),
            unambiguous: Default::default(),
            interop: crate::interop::UnionInterop::default(),
            deny_untagged: Default::default(),
        })
    }
}

/// Result<T, E> is represented as a union: ok(T) | err(E)
impl<T: BuildSchema + 'static, E: BuildSchema + 'static> BuildSchema for Result<T, E> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let ok_schema = ctx.build::<T>();
        let err_schema = ctx.build::<E>();

        SchemaNodeContent::Union(crate::UnionSchema {
            variants: IndexMap::from([
                ("ok".to_string(), ok_schema),
                ("err".to_string(), err_schema),
            ]),
            unambiguous: Default::default(),
            interop: crate::interop::UnionInterop::default(),
            deny_untagged: Default::default(),
        })
    }
}

/// Vec<T> is represented as an array with item type T
impl<T: BuildSchema + 'static> BuildSchema for Vec<T> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let item = ctx.build::<T>();
        SchemaNodeContent::Array(crate::ArraySchema {
            item,
            min_length: None,
            max_length: None,
            unique: false,
            contains: None,
            binding_style: None,
        })
    }
}

/// HashMap<K, V> is represented as a map
impl<K: BuildSchema + 'static, V: BuildSchema + 'static> BuildSchema
    for std::collections::HashMap<K, V>
{
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let key = ctx.build::<K>();
        let value = ctx.build::<V>();
        SchemaNodeContent::Map(crate::MapSchema {
            key,
            value,
            min_size: None,
            max_size: None,
        })
    }
}

/// BTreeMap<K, V> is represented as a map
impl<K: BuildSchema + 'static, V: BuildSchema + 'static> BuildSchema
    for std::collections::BTreeMap<K, V>
{
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let key = ctx.build::<K>();
        let value = ctx.build::<V>();
        SchemaNodeContent::Map(crate::MapSchema {
            key,
            value,
            min_size: None,
            max_size: None,
        })
    }
}

/// IndexMap<K, V> is represented as a map (preserves insertion order)
impl<K: BuildSchema + 'static, V: BuildSchema + 'static> BuildSchema for IndexMap<K, V> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let key = ctx.build::<K>();
        let value = ctx.build::<V>();
        SchemaNodeContent::Map(crate::MapSchema {
            key,
            value,
            min_size: None,
            max_size: None,
        })
    }
}

/// Box<T> delegates to T
impl<T: BuildSchema + 'static> BuildSchema for Box<T> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        T::build_schema(ctx)
    }
}

/// Rc<T> delegates to T
impl<T: BuildSchema + 'static> BuildSchema for std::rc::Rc<T> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        T::build_schema(ctx)
    }
}

/// Arc<T> delegates to T
impl<T: BuildSchema + 'static> BuildSchema for std::sync::Arc<T> {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        T::build_schema(ctx)
    }
}

// Tuples
impl<A: BuildSchema + 'static> BuildSchema for (A,) {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let elements = vec![ctx.build::<A>()];
        SchemaNodeContent::Tuple(crate::TupleSchema {
            elements,
            binding_style: None,
        })
    }
}

impl<A: BuildSchema + 'static, B: BuildSchema + 'static> BuildSchema for (A, B) {
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let elements = vec![ctx.build::<A>(), ctx.build::<B>()];
        SchemaNodeContent::Tuple(crate::TupleSchema {
            elements,
            binding_style: None,
        })
    }
}

impl<A: BuildSchema + 'static, B: BuildSchema + 'static, C: BuildSchema + 'static> BuildSchema
    for (A, B, C)
{
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let elements = vec![ctx.build::<A>(), ctx.build::<B>(), ctx.build::<C>()];
        SchemaNodeContent::Tuple(crate::TupleSchema {
            elements,
            binding_style: None,
        })
    }
}

impl<
    A: BuildSchema + 'static,
    B: BuildSchema + 'static,
    C: BuildSchema + 'static,
    D: BuildSchema + 'static,
> BuildSchema for (A, B, C, D)
{
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let elements = vec![
            ctx.build::<A>(),
            ctx.build::<B>(),
            ctx.build::<C>(),
            ctx.build::<D>(),
        ];
        SchemaNodeContent::Tuple(crate::TupleSchema {
            elements,
            binding_style: None,
        })
    }
}

impl<
    A: BuildSchema + 'static,
    B: BuildSchema + 'static,
    C: BuildSchema + 'static,
    D: BuildSchema + 'static,
    E: BuildSchema + 'static,
> BuildSchema for (A, B, C, D, E)
{
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let elements = vec![
            ctx.build::<A>(),
            ctx.build::<B>(),
            ctx.build::<C>(),
            ctx.build::<D>(),
            ctx.build::<E>(),
        ];
        SchemaNodeContent::Tuple(crate::TupleSchema {
            elements,
            binding_style: None,
        })
    }
}

impl<
    A: BuildSchema + 'static,
    B: BuildSchema + 'static,
    C: BuildSchema + 'static,
    D: BuildSchema + 'static,
    E: BuildSchema + 'static,
    F: BuildSchema + 'static,
> BuildSchema for (A, B, C, D, E, F)
{
    fn build_schema(ctx: &mut SchemaBuilder) -> SchemaNodeContent {
        let elements = vec![
            ctx.build::<A>(),
            ctx.build::<B>(),
            ctx.build::<C>(),
            ctx.build::<D>(),
            ctx.build::<E>(),
            ctx.build::<F>(),
        ];
        SchemaNodeContent::Tuple(crate::TupleSchema {
            elements,
            binding_style: None,
        })
    }
}