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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! Type conversion traits for RON.
//!
//! This module provides [`ToRon`] and [`FromRon`] traits for converting
//! between Rust types and RON values, without requiring serde.
//!
//! # Example
//!
//! ```
//! use ron2::{ToRon, FromRon, Value};
//!
//! // Serialize to RON
//! let numbers = vec![1, 2, 3];
//! let ron_string = numbers.to_ron().unwrap();
//! assert_eq!(ron_string, "[1,2,3]");
//!
//! // Deserialize from RON (now returns SpannedResult for precise error locations)
//! let parsed: Vec<i32> = Vec::from_ron("[1, 2, 3]").unwrap();
//! assert_eq!(parsed, vec![1, 2, 3]);
//! ```

mod impls_collection;
mod impls_primitive;
mod impls_wrapper;
mod map_access;
pub mod number;
mod spanned;

use alloc::string::String;
use std::io::Read;

pub use map_access::AstMapAccess;
pub use number::{ParsedInt, parse_int_raw};
pub use spanned::Spanned;

use crate::{
    Value,
    ast::{Expr, expr_to_value, format_expr, parse_document, value_to_expr},
    error::{Error, ErrorKind, Result},
    fmt::FormatConfig,
};

/// Trait for types that can be converted to RON.
///
/// The core method is [`to_ast`](ToRon::to_ast), which converts to an AST expression.
/// All other methods derive from this.
///
/// # Example
///
/// ```
/// use ron2::ToRon;
///
/// let value = vec![1, 2, 3];
/// let ron_string = value.to_ron().unwrap();
/// assert!(ron_string.contains("1") && ron_string.contains("2") && ron_string.contains("3"));
/// ```
pub trait ToRon {
    /// Convert this value to a RON AST expression.
    ///
    /// This is the core method that all types must implement.
    fn to_ast(&self) -> Result<Expr<'static>>;

    /// Convert this value to a pretty-printed RON string (default format).
    fn to_ron(&self) -> Result<String> {
        Ok(format_expr(&self.to_ast()?, &FormatConfig::default()))
    }

    /// Convert this value to a RON string with custom formatting.
    ///
    /// # Example
    ///
    /// ```
    /// use ron2::{ToRon, fmt::FormatConfig};
    ///
    /// let value = vec![1, 2, 3];
    /// let minimal = value.to_ron_with(&FormatConfig::minimal()).unwrap();
    /// assert_eq!(minimal, "[1,2,3]");
    /// ```
    fn to_ron_with(&self, config: &FormatConfig) -> Result<String> {
        Ok(format_expr(&self.to_ast()?, config))
    }

    /// Convert this value to a RON [`Value`] (via AST).
    fn to_ron_value(&self) -> Result<Value> {
        expr_to_value(&self.to_ast()?)
    }

    /// Convert this value to a typed RON document.
    ///
    /// If `include_type_attribute` is true in the config, the document will
    /// include a `#![type = "..."]` attribute using [`core::any::type_name`].
    fn to_typed_document(&self, config: &SerializeConfig) -> Result<Document<'static>>
    where
        Self: Sized,
    {
        let mut doc = Document {
            source: Cow::Borrowed(""),
            leading: Trivia::empty(),
            attributes: Vec::new(),
            pre_value: Trivia::empty(),
            value: Some(self.to_ast()?),
            trailing: Trivia::empty(),
        };

        if config.include_type_attribute {
            let type_path = core::any::type_name::<Self>();
            doc.attributes.push(Attribute::synthetic_type(type_path));
        }

        Ok(doc)
    }

    /// Convert this value to a typed RON string with default settings.
    ///
    /// This includes the `#![type = "..."]` attribute.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use ron2::ToRon;
    ///
    /// #[derive(Ron)]
    /// struct Config {
    ///     port: u16,
    /// }
    ///
    /// let config = Config { port: 8080 };
    ///
    /// // Serialize with type attribute
    /// let ron = config.to_typed_ron()?;
    /// assert!(ron.starts_with("#![type = \""));
    /// ```
    fn to_typed_ron(&self) -> Result<String>
    where
        Self: Sized,
    {
        let config = SerializeConfig::default();
        let doc = self.to_typed_document(&config)?;
        Ok(format_document(&doc, &config.format))
    }

    /// Convert this value to a typed RON string with custom settings.
    fn to_typed_ron_with(&self, config: &SerializeConfig) -> Result<String>
    where
        Self: Sized,
    {
        let doc = self.to_typed_document(config)?;
        Ok(format_document(&doc, &config.format))
    }
}

/// Trait for types that can be constructed from RON.
///
/// The core method is [`from_ast`](FromRon::from_ast), which deserializes from
/// an AST expression with full span information for error reporting.
///
/// # Example
///
/// ```
/// use ron2::FromRon;
///
/// let values: Vec<i32> = Vec::from_ron("[1, 2, 3]").unwrap();
/// assert_eq!(values, vec![1, 2, 3]);
/// ```
pub trait FromRon: Sized {
    /// Core method: deserialize from an AST expression.
    ///
    /// This has access to the full span information for precise error reporting.
    fn from_ast(expr: &Expr<'_>) -> Result<Self>;

    /// Construct this type from a RON [`Value`].
    ///
    /// This converts the Value to an AST expression with synthetic spans,
    /// then calls [`from_ast`](FromRon::from_ast).
    ///
    /// **Note:** Errors will have synthetic spans (line 0, column 0) since
    /// Values have no source position information. For precise error locations,
    /// use [`from_ron`](FromRon::from_ron) to parse from a string directly.
    /// You can check if a span is synthetic using [`Span::is_synthetic()`](crate::error::Span::is_synthetic).
    fn from_ron_value(value: Value) -> Result<Self> {
        let expr = value_to_expr(value);
        Self::from_ast(&expr)
    }

    /// Parse a RON string and construct this type.
    ///
    /// Returns a [`Result`] with precise error location information.
    fn from_ron(s: &str) -> Result<Self> {
        let doc = parse_document(s)?;
        match doc.value {
            Some(ref expr) => Self::from_ast(expr),
            None => Err(Error::at_start(ErrorKind::Eof)),
        }
    }

    /// Read RON from a reader and construct this type.
    fn from_ron_reader<R: Read>(mut reader: R) -> Result<Self> {
        let mut buf = String::new();
        reader.read_to_string(&mut buf).map_err(|e| {
            Error::at_start(ErrorKind::Io {
                message: e.to_string(),
                source: None,
            })
        })?;
        Self::from_ron(&buf)
    }
}

/// Trait for types that can be deserialized from struct fields.
///
/// This trait is used by the `#[ron(flatten)]` attribute to allow a struct's
/// fields to be merged into a parent struct. Types implementing this trait
/// can consume fields from an [`AstMapAccess`] rather than requiring a
/// separate struct expression.
///
/// This trait is automatically implemented by the `FromRon` derive macro
/// for named structs.
///
/// # Example
///
/// ```ignore
/// #[derive(FromRon)]
/// struct Inner {
///     value: i32,
/// }
///
/// #[derive(FromRon)]
/// struct Outer {
///     name: String,
///     #[ron(flatten)]
///     inner: Inner,  // Fields from Inner are merged into Outer
/// }
///
/// // RON input: (name: "test", value: 42)
/// // Not: (name: "test", inner: (value: 42))
/// ```
pub trait FromRonFields: Sized {
    /// Consume fields from an existing map access to construct this type.
    ///
    /// This is used for `#[ron(flatten)]` fields where the inner struct's
    /// fields appear directly in the parent struct.
    fn from_fields(access: &mut AstMapAccess<'_>) -> Result<Self>;
}

// =============================================================================
// Error helpers (module-local)
// =============================================================================

/// Create an invalid value error.
fn invalid_value(msg: impl Into<String>) -> Error {
    Error::new(crate::error::ErrorKind::Message(msg.into()))
}

/// Extract elements from a sequence-like expression (Seq or Tuple).
pub(crate) fn extract_seq_elements<'a>(
    expr: &'a Expr<'a>,
) -> Option<alloc::vec::Vec<&'a Expr<'a>>> {
    match expr {
        Expr::Seq(seq) => Some(seq.items.iter().map(|item| &item.expr).collect()),
        Expr::Tuple(tuple) => Some(tuple.elements.iter().map(|elem| &elem.expr).collect()),
        _ => None,
    }
}

/// Get a human-readable type name for an AST expression.
#[must_use]
pub fn expr_type_name(expr: &Expr<'_>) -> &'static str {
    match expr {
        Expr::Unit(_) => "unit",
        Expr::Bool(_) => "bool",
        Expr::Char(_) => "char",
        Expr::Byte(_) => "byte",
        Expr::Number(_) => "number",
        Expr::String(_) => "string",
        Expr::Bytes(_) => "bytes",
        Expr::Option(_) => "option",
        Expr::Seq(_) => "sequence",
        Expr::Map(_) => "map",
        Expr::Tuple(_) => "tuple",
        Expr::AnonStruct(_) => "struct",
        Expr::Struct(_) => "named",
        Expr::Error(_) => "error",
    }
}

/// Create a spanned type mismatch error.
pub(crate) fn spanned_type_mismatch(expected: &str, expr: &Expr<'_>) -> Error {
    Error::with_span(
        ErrorKind::TypeMismatch {
            expected: expected.into(),
            found: expr_type_name(expr).into(),
        },
        *expr.span(),
    )
}

/// Create a spanned error with the given code and expression's span.
pub(crate) fn spanned_err(err: Error, expr: &Expr<'_>) -> Error {
    if err.span().is_synthetic() {
        Error::with_span(err.kind().clone(), *expr.span())
    } else {
        err
    }
}

// =============================================================================
// ToRon implementation for Value
// =============================================================================

impl ToRon for Value {
    fn to_ast(&self) -> Result<Expr<'static>> {
        // Clone self and convert to AST using value_to_expr
        Ok(crate::ast::value_to_expr(self.clone()))
    }
}

impl FromRon for Value {
    fn from_ast(expr: &Expr<'_>) -> Result<Self> {
        expr_to_value(expr)
    }
}

// =============================================================================
// SerializeConfig
// =============================================================================

use alloc::borrow::Cow;

use crate::{
    ast::{Attribute, Document, Trivia},
    fmt::format_document,
};

/// Configuration for serializing typed RON documents.
///
/// This controls how types are serialized to RON format, including whether
/// to include the `#![type = "..."]` attribute for LSP support.
///
/// # Example
///
/// ```ignore
/// use ron2::{ToRon, SerializeConfig};
///
/// let config = Config { port: 8080 };
///
/// // With type attribute (default)
/// let ron = config.to_typed_ron()?;
/// // #![type = "my_crate::Config"]
/// //
/// // Config(port: 8080)
///
/// // Without type attribute
/// let ron = config.to_typed_ron_with(&SerializeConfig::without_type_attribute())?;
/// // Config(port: 8080)
/// ```
#[derive(Clone, Debug)]
pub struct SerializeConfig {
    /// Format configuration for the output.
    pub format: FormatConfig,
    /// Whether to include the `#![type = "..."]` attribute.
    pub include_type_attribute: bool,
}

impl Default for SerializeConfig {
    fn default() -> Self {
        Self {
            format: FormatConfig::default(),
            include_type_attribute: true,
        }
    }
}

impl SerializeConfig {
    /// Create a new `SerializeConfig` with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a config that excludes the type attribute.
    #[must_use]
    pub fn without_type_attribute() -> Self {
        Self {
            include_type_attribute: false,
            ..Default::default()
        }
    }

    /// Set the format configuration.
    #[must_use]
    pub fn format(mut self, format: FormatConfig) -> Self {
        self.format = format;
        self
    }

    /// Set whether to include the type attribute.
    #[must_use]
    pub fn type_attribute(mut self, include: bool) -> Self {
        self.include_type_attribute = include;
        self
    }
}

#[cfg(test)]
mod tests {
    use alloc::{collections::BTreeMap, vec, vec::Vec};

    use super::*;

    /// Helper to get minimal (compact) output
    fn minimal(v: &impl ToRon) -> String {
        v.to_ron_with(&FormatConfig::minimal()).unwrap()
    }

    #[test]
    fn test_primitives_to_ron() {
        assert_eq!(minimal(&true), "true");
        assert_eq!(minimal(&false), "false");
        assert_eq!(minimal(&42i32), "42");
        assert_eq!(minimal(&(-10i8)), "-10");
        assert_eq!(minimal(&'a'), "'a'");
        assert_eq!(minimal(&"hello"), "\"hello\"");
        assert_eq!(minimal(&()), "()");
    }

    #[test]
    fn test_primitives_from_ron() {
        assert!(bool::from_ron("true").unwrap());
        assert!(!bool::from_ron("false").unwrap());
        assert_eq!(i32::from_ron("42").unwrap(), 42);
        assert_eq!(i32::from_ron("-10").unwrap(), -10);
        assert_eq!(char::from_ron("'a'").unwrap(), 'a');
        assert_eq!(String::from_ron("\"hello\"").unwrap(), "hello");
        assert_eq!(<()>::from_ron("()").unwrap(), ());
    }

    #[test]
    fn test_floats() {
        assert!((f32::from_ron("1.5").unwrap() - 1.5).abs() < 0.001);
        assert!((f64::from_ron("2.5").unwrap() - 2.5).abs() < 0.00001);
        // Integers should also work as floats
        assert!((f64::from_ron("42").unwrap() - 42.0).abs() < 0.00001);
    }

    #[test]
    fn test_collections() {
        // Note: ron2's Minimal format doesn't add spaces after commas
        assert_eq!(minimal(&vec![1, 2, 3]), "[1,2,3]");
        assert_eq!(minimal(&Vec::<i32>::new()), "[]");

        assert_eq!(Vec::<i32>::from_ron("[1, 2, 3]").unwrap(), vec![1, 2, 3]);
        assert_eq!(Vec::<i32>::from_ron("[]").unwrap(), Vec::<i32>::new());
    }

    #[test]
    fn test_option() {
        assert_eq!(minimal(&Some(42)), "Some(42)");
        assert_eq!(minimal(&Option::<i32>::None), "None");

        assert_eq!(Option::<i32>::from_ron("Some(42)").unwrap(), Some(42));
        assert_eq!(Option::<i32>::from_ron("None").unwrap(), None);
        // Raw value as implicit Some
        assert_eq!(Option::<i32>::from_ron("42").unwrap(), Some(42));
    }

    #[test]
    fn test_tuple() {
        // ron2 serializes tuples as (a, b)
        let tuple_ron = minimal(&(1, 2));
        assert!(tuple_ron.contains('1') && tuple_ron.contains('2'));

        assert_eq!(<(i32, i32)>::from_ron("(1, 2)").unwrap(), (1, 2));
        assert_eq!(
            <(i32, String, bool)>::from_ron("(1, \"hello\", true)").unwrap(),
            (1, "hello".to_string(), true)
        );
    }

    #[test]
    fn test_map() {
        let mut map = BTreeMap::new();
        map.insert("a".to_string(), 1);
        map.insert("b".to_string(), 2);
        let ron = minimal(&map);
        assert!(ron.contains("\"a\""));
        assert!(ron.contains("\"b\""));

        let ron = r#"{"a": 1, "b": 2}"#;
        let parsed: BTreeMap<String, i32> = BTreeMap::from_ron(ron).unwrap();
        assert_eq!(parsed.get("a"), Some(&1));
        assert_eq!(parsed.get("b"), Some(&2));
    }

    #[test]
    fn test_array() {
        assert_eq!(<[i32; 3]>::from_ron("[1, 2, 3]").unwrap(), [1, 2, 3]);
    }

    #[test]
    fn test_integer_range() {
        assert!(i8::from_ron("127").is_ok());
        assert!(i8::from_ron("128").is_err());
        assert!(u8::from_ron("255").is_ok());
        assert!(u8::from_ron("256").is_err());
        assert!(u8::from_ron("-1").is_err());
    }

    #[test]
    fn test_ast_map_access() {
        use crate::ast::parse_document;

        let ron = r#"(name: "test", value: 42)"#;
        let doc = parse_document(ron).unwrap();

        // Get the anonymous struct from the document
        if let Some(Expr::AnonStruct(s)) = &doc.value {
            let mut access = AstMapAccess::from_anon(s, Some("TestStruct")).unwrap();

            assert_eq!(access.required::<String>("name").unwrap(), "test");
            assert_eq!(access.required::<i32>("value").unwrap(), 42);
            assert!(access.deny_unknown_fields(&["name", "value"]).is_ok());
        } else {
            panic!("Expected anonymous struct");
        }
    }

    #[test]
    fn test_spanned_error_line_numbers() {
        // Type mismatch on line 1 - expected i32, got string
        let err = i32::from_ron(r#""not a number""#).unwrap_err();
        assert_eq!(err.span().start.line, 1);
        assert_eq!(err.span().start.col, 1);
        assert_eq!(err.span().end.line, 1);
        assert_eq!(err.span().end.col, 15);

        // Type mismatch on line 3 in a multiline document
        let input = r#"[
    1,
    "wrong",
    3
]"#;
        let err = Vec::<i32>::from_ron(input).unwrap_err();
        assert_eq!(err.span().start.line, 3);
        assert_eq!(err.span().start.col, 5);
        assert_eq!(err.span().end.line, 3);
        assert_eq!(err.span().end.col, 12);

        // Nested structure - tuple with wrong type in second position
        let input = r#"(
    100,
    "not an int"
)"#;
        let err = <(i32, i32)>::from_ron(input).unwrap_err();
        // The error should point to "not an int" on line 3
        assert_eq!(err.span().start.line, 3);

        // Integer out of range
        let err = i8::from_ron("128").unwrap_err();
        assert_eq!(err.span().start.line, 1);
        assert_eq!(err.span().start.col, 1);

        // Boolean type mismatch
        let err = bool::from_ron("42").unwrap_err();
        assert_eq!(err.span().start.line, 1);
        assert!(matches!(
            err.kind(),
            crate::error::ErrorKind::TypeMismatch { .. }
        ));
    }

    #[test]
    fn test_spanned_error_in_map() {
        let input = r#"{
    "a": 1,
    "b": "wrong"
}"#;
        let err = BTreeMap::<String, i32>::from_ron(input).unwrap_err();
        // Error should point to "wrong" on line 3
        assert_eq!(err.span().start.line, 3);
        assert_eq!(err.span().start.col, 10);
    }

    #[test]
    fn test_from_ron_value_strips_span() {
        use crate::Value;
        // from_ron_value returns Result (not SpannedResult) since Value has no span
        let value = Value::String("not a number".to_string());
        let err = i32::from_ron_value(value).unwrap_err();
        // The error should still have the correct error code
        assert!(matches!(
            err.kind(),
            crate::error::ErrorKind::TypeMismatch { .. }
        ));
    }

    #[test]
    fn test_indexmap() {
        use indexmap::IndexMap;

        // ToRon
        let mut map: IndexMap<String, i32> = IndexMap::default();
        map.insert("first".to_string(), 1);
        map.insert("second".to_string(), 2);
        let ron = map.to_ron().unwrap();
        assert!(ron.contains("\"first\""));
        assert!(ron.contains("\"second\""));

        // FromRon - order should be preserved
        let ron = r#"{"a": 1, "b": 2, "c": 3}"#;
        let parsed: IndexMap<String, i32> = IndexMap::from_ron(ron).unwrap();
        let keys: Vec<_> = parsed.keys().collect();
        assert_eq!(keys, vec!["a", "b", "c"]);
        assert_eq!(parsed.get("a"), Some(&1));
        assert_eq!(parsed.get("b"), Some(&2));
        assert_eq!(parsed.get("c"), Some(&3));
    }

    #[test]
    fn test_indexset() {
        use indexmap::IndexSet;

        // ToRon
        let mut set: IndexSet<i32> = IndexSet::default();
        set.insert(3);
        set.insert(1);
        set.insert(2);
        let ron = set.to_ron().unwrap();
        assert!(ron.contains('3'));
        assert!(ron.contains('1'));
        assert!(ron.contains('2'));

        // FromRon - order should be preserved
        let ron = "[3, 1, 2]";
        let parsed: IndexSet<i32> = IndexSet::from_ron(ron).unwrap();
        let values: Vec<_> = parsed.iter().copied().collect();
        assert_eq!(values, vec![3, 1, 2]);
    }

    #[test]
    fn test_value_from_ron() {
        use crate::value::Number;

        // Simple number
        let value: Value = Value::from_ron("42").unwrap();
        assert_eq!(value, Value::Number(Number::U8(42)));

        // String
        let value: Value = Value::from_ron(r#""hello""#).unwrap();
        assert_eq!(value, Value::String("hello".to_string()));

        // Boolean
        let value: Value = Value::from_ron("true").unwrap();
        assert_eq!(value, Value::Bool(true));

        // Sequence
        let value: Value = Value::from_ron("[1, 2, 3]").unwrap();
        assert_eq!(
            value,
            Value::Seq(vec![
                Value::Number(Number::U8(1)),
                Value::Number(Number::U8(2)),
                Value::Number(Number::U8(3)),
            ])
        );

        // Anonymous struct
        let value: Value = Value::from_ron(r#"(name: "test", count: 5)"#).unwrap();
        if let Value::Struct(fields) = value {
            assert_eq!(fields.len(), 2);
            assert_eq!(
                fields[0],
                ("name".to_string(), Value::String("test".to_string()))
            );
            assert_eq!(
                fields[1],
                ("count".to_string(), Value::Number(Number::U8(5)))
            );
        } else {
            panic!("Expected Struct, got {value:?}");
        }

        // Option
        let value: Value = Value::from_ron("Some(42)").unwrap();
        assert_eq!(
            value,
            Value::Option(Some(Box::new(Value::Number(Number::U8(42)))))
        );

        let value: Value = Value::from_ron("None").unwrap();
        assert_eq!(value, Value::Option(None));
    }

    #[test]
    fn test_serialize_config_default() {
        let config = super::SerializeConfig::default();
        assert!(config.include_type_attribute);
    }

    #[test]
    fn test_serialize_config_without_type_attribute() {
        let config = super::SerializeConfig::without_type_attribute();
        assert!(!config.include_type_attribute);
    }

    #[test]
    fn test_serialize_config_builder() {
        let config = super::SerializeConfig::new()
            .type_attribute(false)
            .format(FormatConfig::minimal());
        assert!(!config.include_type_attribute);
    }

    #[test]
    fn test_to_typed_ron_includes_type_attribute() {
        use super::ToRon;

        // All types now include type attribute using std::any::type_name
        let result = 42i32.to_typed_ron().unwrap();
        assert!(result.contains("#![type = \"i32\"]"));
        assert!(result.contains("42"));

        let hello = "hello".to_string();
        let result = hello.to_typed_ron().unwrap();
        assert!(result.contains("#![type"));
        assert!(result.contains("String"));
        assert!(result.contains("hello"));

        let result = vec![1, 2, 3].to_typed_ron().unwrap();
        assert!(result.contains("#![type"));
        assert!(result.contains("Vec"));
    }

    #[test]
    fn test_to_typed_document_structure() {
        use super::ToRon;

        let config = super::SerializeConfig::default();
        let doc = 42i32.to_typed_document(&config).unwrap();

        // Should have a value and a type attribute
        assert!(doc.value.is_some());
        assert_eq!(doc.attributes.len(), 1);
    }

    #[test]
    fn test_to_typed_ron_with_config() {
        use super::ToRon;

        let config =
            super::SerializeConfig::without_type_attribute().format(FormatConfig::minimal());

        let result = vec![1, 2, 3].to_typed_ron_with(&config).unwrap();
        assert_eq!(result, "[1,2,3]");
    }
}