ron2 0.3.0

RON parser with full AST access, perfect round-trip fidelity, and formatting tools
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
//! Traits for the RON schema system.
//!
//! This module provides traits that types can implement to participate in the
//! schema system. By implementing these traits, custom types can be recognized
//! as lists, maps, or other schema-compatible types.
//!
//! # Example
//!
//! ```rust
//! use crate::schema::{RonSchema, RonList, TypeKind};
//!
//! // A custom list type
//! struct MyVec<T>(Vec<T>);
//!
//! impl<T: RonSchema> RonSchema for MyVec<T> {
//!     fn type_kind() -> TypeKind {
//!         TypeKind::List(Box::new(T::type_kind()))
//!     }
//! }
//!
//! // Mark it as a list type
//! impl<T: RonSchema> RonList for MyVec<T> {
//!     type Element = T;
//! }
//! ```

use alloc::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, LinkedList, VecDeque},
    rc::Rc,
    sync::Arc,
};
use core::{
    cell::{Cell, RefCell},
    hash::BuildHasher,
    marker::PhantomData,
};
use std::collections::{HashMap, HashSet};
#[cfg(feature = "derive")]
use std::path::{Path, PathBuf};

#[cfg(feature = "derive")]
use crate::schema::SchemaError;
#[cfg(feature = "derive")]
use crate::schema::error::StorageError;
use crate::schema::{Schema, TypeKind, collect::SchemaEntry};

/// Core trait for types that can be represented in the RON schema system.
///
/// This trait is the foundation of the schema system. Types that implement
/// this trait can be used in schemas and will be properly recognized during
/// validation and LSP operations.
///
/// # Implementing for Custom Types
///
/// For most custom structs and enums, use `#[derive(RonSchema)]` which
/// generates a complete implementation including schema storage support.
///
/// For wrapper types or newtypes that should behave like existing types,
/// implement this trait manually:
///
/// ```rust
/// use crate::schema::{RonSchema, TypeKind};
///
/// struct UserId(u64);
///
/// impl RonSchema for UserId {
///     fn type_kind() -> TypeKind {
///         TypeKind::U64  // UserId serializes as a u64
///     }
/// }
/// ```
pub trait RonSchema {
    /// Returns the `TypeKind` that represents this type in the schema system.
    fn type_kind() -> TypeKind;

    /// Returns optional documentation for this type.
    ///
    /// Override this to provide documentation that appears in the schema.
    #[must_use]
    fn type_doc() -> Option<&'static str> {
        None
    }

    /// Returns the complete schema for this type, including documentation.
    ///
    /// The default implementation constructs a schema from `type_kind()` and `type_doc()`.
    /// Types using `#[derive(RonSchema)]` will override this with a more complete
    /// implementation that includes field-level documentation.
    #[must_use]
    fn schema() -> Schema {
        Schema {
            doc: Self::type_doc().map(str::to_string),
            kind: Self::type_kind(),
        }
    }

    /// Returns the fully-qualified type path for this type.
    ///
    /// This is used to locate schema files and for `TypeRef` references.
    /// Returns `None` for primitive types and standard library types.
    #[must_use]
    fn type_path() -> Option<&'static str> {
        None
    }

    /// Returns the direct child schemas referenced by this type.
    ///
    /// This is a non-recursive list; use `collect_schemas` or `write_schemas`
    /// to traverse the full schema graph.
    #[must_use]
    fn child_schemas() -> &'static [&'static SchemaEntry] {
        &[]
    }

    /// Writes the schema to the specified output directory.
    ///
    /// If `output_dir` is `None`, the schema is written to the default location
    /// determined by `RON_SCHEMA_DIR` env var or XDG data directory.
    ///
    /// Returns the path to the written schema file, or `None` if this type
    /// doesn't support schema storage (e.g., primitive types).
    ///
    /// Only available when the `derive` feature is enabled.
    #[cfg(feature = "derive")]
    fn write_schema(output_dir: Option<&Path>) -> Result<PathBuf, SchemaError> {
        let type_path = Self::type_path().ok_or_else(|| {
            SchemaError::Storage(StorageError::Io(
                "type does not support schema storage".to_string(),
            ))
        })?;
        let schema = Self::schema();
        super::write_schema(type_path, &schema, output_dir)
    }

    /// Writes this type's schema and all child schemas recursively.
    ///
    /// Only available when the `derive` feature is enabled.
    #[cfg(feature = "derive")]
    fn write_schemas(output_dir: Option<&str>) -> Result<Vec<PathBuf>, SchemaError>
    where
        Self: Sized,
    {
        super::write_schemas::<Self>(output_dir)
    }
}

/// Marker trait for types that behave like lists/sequences.
///
/// Implement this trait alongside `RonSchema` to mark a type as list-like.
/// This allows the LSP and validation system to treat your custom type as a
/// sequence when providing completions and validating values.
///
/// # Example
///
/// ```rust
/// use crate::schema::{RonSchema, RonList, TypeKind};
///
/// struct SortedVec<T>(Vec<T>);
///
/// impl<T: RonSchema> RonSchema for SortedVec<T> {
///     fn type_kind() -> TypeKind {
///         TypeKind::List(Box::new(T::type_kind()))
///     }
/// }
///
/// impl<T: RonSchema> RonList for SortedVec<T> {
///     type Element = T;
/// }
/// ```
pub trait RonList: RonSchema {
    /// The element type of this list.
    type Element: RonSchema;

    /// Returns the `TypeKind` of the element type.
    #[must_use]
    fn element_type_kind() -> TypeKind {
        Self::Element::type_kind()
    }
}

/// Marker trait for types that behave like maps/dictionaries.
///
/// Implement this trait alongside `RonSchema` to mark a type as map-like.
/// This allows the LSP and validation system to treat your custom type as a
/// map when providing completions and validating values.
///
/// # Example
///
/// ```rust
/// use crate::schema::{RonSchema, RonMap, TypeKind};
/// use std::collections::BTreeMap;
///
/// struct OrderedMap<K, V>(BTreeMap<K, V>);
///
/// impl<K: RonSchema, V: RonSchema> RonSchema for OrderedMap<K, V> {
///     fn type_kind() -> TypeKind {
///         TypeKind::Map {
///             key: Box::new(K::type_kind()),
///             value: Box::new(V::type_kind()),
///         }
///     }
/// }
///
/// impl<K: RonSchema, V: RonSchema> RonMap for OrderedMap<K, V> {
///     type Key = K;
///     type Value = V;
/// }
/// ```
pub trait RonMap: RonSchema {
    /// The key type of this map.
    type Key: RonSchema;
    /// The value type of this map.
    type Value: RonSchema;

    /// Returns the `TypeKind` of the key type.
    #[must_use]
    fn key_type_kind() -> TypeKind {
        Self::Key::type_kind()
    }

    /// Returns the `TypeKind` of the value type.
    #[must_use]
    fn value_type_kind() -> TypeKind {
        Self::Value::type_kind()
    }
}

/// Marker trait for types that behave like optional values.
///
/// Implement this trait alongside `RonSchema` to mark a type as optional-like.
/// This is primarily used for `Option<T>` but can be implemented for custom
/// nullable/optional wrapper types.
pub trait RonOptional: RonSchema {
    /// The inner type when the optional contains a value.
    type Inner: RonSchema;

    /// Returns the `TypeKind` of the inner type.
    #[must_use]
    fn inner_type_kind() -> TypeKind {
        Self::Inner::type_kind()
    }
}

// =============================================================================
// Macro Definitions for Repetitive Implementations
// =============================================================================

/// Implements `RonSchema` for primitive types with a direct `TypeKind` mapping.
macro_rules! impl_primitive_schema {
    ($($ty:ty => $variant:ident),* $(,)?) => {
        $(
            impl RonSchema for $ty {
                fn type_kind() -> TypeKind {
                    TypeKind::$variant
                }
            }
        )*
    };
}

/// Implements `RonSchema` for transparent wrapper types that delegate to their inner type.
macro_rules! impl_transparent_schema {
    ($($ty:ident),* $(,)?) => {
        $(
            impl<T: RonSchema> RonSchema for $ty<T> {
                fn type_kind() -> TypeKind {
                    T::type_kind()
                }
            }
        )*
    };
}

/// Implements `RonSchema` and `RonList` for list-like collection types.
macro_rules! impl_list_schema {
    ($($ty:ty),* $(,)?) => {
        $(
            impl<T: RonSchema> RonSchema for $ty {
                fn type_kind() -> TypeKind {
                    TypeKind::List(Box::new(T::type_kind()))
                }
            }

            impl<T: RonSchema> RonList for $ty {
                type Element = T;
            }
        )*
    };
}

/// Implements `RonSchema` for tuple types.
macro_rules! impl_tuple_schema {
    ($($T:ident),+) => {
        impl<$($T: RonSchema),+> RonSchema for ($($T,)+) {
            fn type_kind() -> TypeKind {
                TypeKind::Tuple(alloc::vec![$($T::type_kind()),+])
            }
        }
    };
}

/// Recursively generates tuple implementations from 1-tuple to N-tuple.
macro_rules! impl_tuple_schema_all {
    () => {};
    ($first:ident $(, $rest:ident)*) => {
        impl_tuple_schema!($first $(, $rest)*);
        impl_tuple_schema_all!($($rest),*);
    };
}

// =============================================================================
// Standard Library Implementations
// =============================================================================

// Primitives

impl_primitive_schema! {
    bool => Bool,
    i8 => I8, i16 => I16, i32 => I32, i64 => I64, i128 => I128, isize => I64,
    u8 => U8, u16 => U16, u32 => U32, u64 => U64, u128 => U128, usize => U64,
    f32 => F32, f64 => F64,
    char => Char,
    String => String,
    () => Unit,
    std::path::PathBuf => String,
    std::path::Path => String,
    std::ffi::OsString => String,
    std::ffi::OsStr => String,
}

// &str is a reference type, not handled by the macro
impl RonSchema for &str {
    fn type_kind() -> TypeKind {
        TypeKind::String
    }
}

// Option<T>

impl<T: RonSchema> RonSchema for Option<T> {
    fn type_kind() -> TypeKind {
        TypeKind::Option(Box::new(T::type_kind()))
    }
}

impl<T: RonSchema> RonOptional for Option<T> {
    type Inner = T;
}

// List-like collections

impl_list_schema! { Vec<T>, VecDeque<T>, LinkedList<T>, BTreeSet<T> }

// Slices and arrays (special cases with unsized/const generic)

impl<T: RonSchema> RonSchema for [T] {
    fn type_kind() -> TypeKind {
        TypeKind::List(Box::new(T::type_kind()))
    }
}

impl<T: RonSchema, const N: usize> RonSchema for [T; N] {
    fn type_kind() -> TypeKind {
        // Arrays are represented as lists with a known length
        // For now, we just use List; we could add a dedicated Array variant
        TypeKind::List(Box::new(T::type_kind()))
    }
}

impl<T: RonSchema, const N: usize> RonList for [T; N] {
    type Element = T;
}

// HashMap and BTreeMap

impl<K: RonSchema, V: RonSchema, S: BuildHasher> RonSchema for HashMap<K, V, S> {
    fn type_kind() -> TypeKind {
        TypeKind::Map {
            key: Box::new(K::type_kind()),
            value: Box::new(V::type_kind()),
        }
    }
}

impl<K: RonSchema, V: RonSchema, S: BuildHasher> RonMap for HashMap<K, V, S> {
    type Key = K;
    type Value = V;
}

impl<K: RonSchema, V: RonSchema> RonSchema for BTreeMap<K, V> {
    fn type_kind() -> TypeKind {
        TypeKind::Map {
            key: Box::new(K::type_kind()),
            value: Box::new(V::type_kind()),
        }
    }
}

impl<K: RonSchema, V: RonSchema> RonMap for BTreeMap<K, V> {
    type Key = K;
    type Value = V;
}

// HashSet (special case with BuildHasher bound)

impl<T: RonSchema, S: BuildHasher> RonSchema for HashSet<T, S> {
    fn type_kind() -> TypeKind {
        TypeKind::List(Box::new(T::type_kind()))
    }
}

impl<T: RonSchema, S: BuildHasher> RonList for HashSet<T, S> {
    type Element = T;
}

// Transparent wrapper types

impl_transparent_schema! { Box, Rc, Arc, Cell, RefCell }

// Mutex and RwLock (special module paths)

impl<T: RonSchema> RonSchema for std::sync::Mutex<T> {
    fn type_kind() -> TypeKind {
        T::type_kind()
    }
}

impl<T: RonSchema> RonSchema for std::sync::RwLock<T> {
    fn type_kind() -> TypeKind {
        T::type_kind()
    }
}

// Cow (special bounds: ToOwned + ?Sized)

impl<T: RonSchema + ToOwned + ?Sized> RonSchema for Cow<'_, T> {
    fn type_kind() -> TypeKind {
        T::type_kind()
    }
}

// Tuples (up to 12 elements like serde)

impl_tuple_schema_all!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);

// PathBuf and Path

// PhantomData (special ?Sized bound)

impl<T: ?Sized> RonSchema for PhantomData<T> {
    fn type_kind() -> TypeKind {
        TypeKind::Unit
    }
}

// Spanned<T> - transparent wrapper that captures source spans

impl<T: RonSchema> RonSchema for crate::convert::Spanned<T> {
    fn type_kind() -> TypeKind {
        // Spanned<T> has the same schema as T (span is deserialization metadata)
        T::type_kind()
    }

    fn type_doc() -> Option<&'static str> {
        // Forward documentation from inner type
        T::type_doc()
    }

    fn schema() -> Schema {
        // Forward complete schema from inner type
        T::schema()
    }

    fn type_path() -> Option<&'static str> {
        // Forward type path from inner type
        T::type_path()
    }
}

// Mark Spanned<T> as optional if T is optional
impl<T: RonOptional> RonOptional for crate::convert::Spanned<T> {
    type Inner = T;
}

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

    #[test]
    fn test_primitive_type_kinds() {
        assert_eq!(bool::type_kind(), TypeKind::Bool);
        assert_eq!(i32::type_kind(), TypeKind::I32);
        assert_eq!(u64::type_kind(), TypeKind::U64);
        assert_eq!(f64::type_kind(), TypeKind::F64);
        assert_eq!(char::type_kind(), TypeKind::Char);
        assert_eq!(String::type_kind(), TypeKind::String);
        assert_eq!(<()>::type_kind(), TypeKind::Unit);
    }

    #[test]
    fn test_option_type_kind() {
        assert_eq!(
            Option::<i32>::type_kind(),
            TypeKind::Option(Box::new(TypeKind::I32))
        );
    }

    #[test]
    fn test_vec_type_kind() {
        assert_eq!(
            Vec::<String>::type_kind(),
            TypeKind::List(Box::new(TypeKind::String))
        );
    }

    #[test]
    fn test_hashmap_type_kind() {
        assert_eq!(
            std::collections::HashMap::<String, i32>::type_kind(),
            TypeKind::Map {
                key: Box::new(TypeKind::String),
                value: Box::new(TypeKind::I32),
            }
        );
    }

    #[test]
    fn test_tuple_type_kind() {
        assert_eq!(
            <(i32, String)>::type_kind(),
            TypeKind::Tuple(vec![TypeKind::I32, TypeKind::String])
        );
    }

    #[test]
    fn test_box_transparent() {
        assert_eq!(Box::<i32>::type_kind(), TypeKind::I32);
    }

    #[test]
    fn test_custom_list_type() {
        // Simulate a custom list type
        #[allow(dead_code)]
        struct MyVec<T>(Vec<T>);

        impl<T: RonSchema> RonSchema for MyVec<T> {
            fn type_kind() -> TypeKind {
                TypeKind::List(Box::new(T::type_kind()))
            }
        }

        impl<T: RonSchema> RonList for MyVec<T> {
            type Element = T;
        }

        assert_eq!(
            MyVec::<i32>::type_kind(),
            TypeKind::List(Box::new(TypeKind::I32))
        );
        assert_eq!(MyVec::<i32>::element_type_kind(), TypeKind::I32);
    }

    #[test]
    fn test_custom_map_type() {
        // Simulate a custom map type
        #[allow(dead_code)]
        struct MyMap<K, V>(std::collections::HashMap<K, V>);

        impl<K: RonSchema, V: RonSchema> RonSchema for MyMap<K, V> {
            fn type_kind() -> TypeKind {
                TypeKind::Map {
                    key: Box::new(K::type_kind()),
                    value: Box::new(V::type_kind()),
                }
            }
        }

        impl<K: RonSchema, V: RonSchema> RonMap for MyMap<K, V> {
            type Key = K;
            type Value = V;
        }

        assert_eq!(
            MyMap::<String, i32>::type_kind(),
            TypeKind::Map {
                key: Box::new(TypeKind::String),
                value: Box::new(TypeKind::I32),
            }
        );
        assert_eq!(MyMap::<String, i32>::key_type_kind(), TypeKind::String);
        assert_eq!(MyMap::<String, i32>::value_type_kind(), TypeKind::I32);
    }

    #[test]
    fn test_spanned_schema_is_transparent() {
        use crate::convert::Spanned;

        // Spanned<T> has the same schema as T
        assert_eq!(Spanned::<i32>::type_kind(), i32::type_kind());
        assert_eq!(Spanned::<String>::type_kind(), String::type_kind());
        assert_eq!(
            Spanned::<Option<bool>>::type_kind(),
            Option::<bool>::type_kind()
        );
        assert_eq!(Spanned::<Vec<i32>>::type_kind(), Vec::<i32>::type_kind());
    }

    #[test]
    fn test_spanned_nested_transparency() {
        use crate::convert::Spanned;

        // Nested Spanned<T> still has the same schema as T
        assert_eq!(Spanned::<Spanned<i32>>::type_kind(), i32::type_kind());
    }

    #[test]
    fn test_spanned_option_combinations() {
        use crate::convert::Spanned;

        // Both Option<Spanned<T>> and Spanned<Option<T>> have Option<T> schema
        assert_eq!(
            Option::<Spanned<i32>>::type_kind(),
            Option::<i32>::type_kind()
        );
        assert_eq!(
            Spanned::<Option<i32>>::type_kind(),
            Option::<i32>::type_kind()
        );
    }
}