rson-core 1.0.0

Core parsing and value types for RSON
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
//! RSON formatter for converting `RsonValue` back to text.
//!
//! This module provides functionality to format RSON values as human-readable text,
//! with configurable formatting options for indentation, spacing, and style.

use crate::{RsonValue, RsonError, RsonResult};
use core::fmt::Write;

#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};

/// Configuration options for RSON formatting.
#[derive(Debug, Clone)]
pub struct FormatOptions {
    /// Number of spaces per indentation level
    pub indent_size: usize,
    /// Whether to use compact mode (minimal whitespace)
    pub compact: bool,
    /// Whether to include trailing commas
    pub trailing_commas: bool,
    /// Maximum line length before wrapping
    pub max_line_length: usize,
    /// Whether to sort map keys
    pub sort_keys: bool,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            indent_size: 2,
            compact: false,
            trailing_commas: true,
            max_line_length: 80,
            sort_keys: false,
        }
    }
}

impl FormatOptions {
    /// Create compact formatting options.
    pub fn compact() -> Self {
        Self {
            compact: true,
            trailing_commas: false,
            ..Default::default()
        }
    }
    
    /// Create pretty formatting options.
    pub fn pretty() -> Self {
        Self {
            compact: false,
            trailing_commas: true,
            indent_size: 2,
            ..Default::default()
        }
    }
}

/// RSON formatter.
pub struct Formatter<'a> {
    options: &'a FormatOptions,
    output: String,
    indent_level: usize,
}

impl<'a> Formatter<'a> {
    /// Create a new formatter with the given options.
    pub fn new(options: &'a FormatOptions) -> Self {
        Self {
            options,
            output: String::new(),
            indent_level: 0,
        }
    }
    
    /// Format a value and return the result.
    pub fn format(mut self, value: &RsonValue) -> RsonResult<String> {
        self.format_value(value)?;
        Ok(self.output)
    }
    
    /// Format a value to the internal buffer.
    fn format_value(&mut self, value: &RsonValue) -> RsonResult<()> {
        match value {
            RsonValue::Null => self.write_str("null"),
            RsonValue::Bool(b) => self.write_str(&b.to_string()),
            RsonValue::Int(i) => self.write_str(&i.to_string()),
            RsonValue::Float(f) => self.write_str(&f.to_string()),
            RsonValue::String(s) => self.format_string(s),
            RsonValue::Char(c) => self.format_char(*c),
            RsonValue::Array(arr) => self.format_array(arr),
            RsonValue::Map(map) => self.format_map(map),
            RsonValue::Struct { name, fields } => self.format_struct(name, fields),
            RsonValue::Tuple(values) => self.format_tuple(values),
            RsonValue::Enum { name, variant, value } => self.format_enum(name, variant, value.as_ref().map(|v| &**v)),
            RsonValue::Option(opt) => self.format_option(opt.as_ref().map(|v| &**v)),
        }
    }
    
    /// Write a string to the output.
    fn write_str(&mut self, s: &str) -> RsonResult<()> {
        self.output.push_str(s);
        Ok(())
    }
    
    /// Write a character to the output.
    fn write_char(&mut self, c: char) -> RsonResult<()> {
        self.output.push(c);
        Ok(())
    }
    
    /// Write indentation.
    fn write_indent(&mut self) -> RsonResult<()> {
        if !self.options.compact {
            for _ in 0..(self.indent_level * self.options.indent_size) {
                self.write_char(' ')?;
            }
        }
        Ok(())
    }
    
    /// Write a newline (unless in compact mode).
    fn write_newline(&mut self) -> RsonResult<()> {
        if !self.options.compact {
            self.write_char('\n')?;
        }
        Ok(())
    }
    
    /// Write a space (unless in compact mode).
    fn write_space(&mut self) -> RsonResult<()> {
        if !self.options.compact {
            self.write_char(' ')?;
        }
        Ok(())
    }
    
    /// Format a string value with proper escaping.
    fn format_string(&mut self, s: &str) -> RsonResult<()> {
        self.write_char('"')?;
        for c in s.chars() {
            match c {
                '"' => self.write_str("\\\"")?,
                '\\' => self.write_str("\\\\")?,
                '\n' => self.write_str("\\n")?,
                '\r' => self.write_str("\\r")?,
                '\t' => self.write_str("\\t")?,
                '\0' => self.write_str("\\0")?,
                c if c.is_control() => {
                    write!(self.output, "\\u{:04x}", c as u32)
                        .map_err(|_| RsonError::custom("Failed to write Unicode escape"))?;
                }
                c => self.write_char(c)?,
            }
        }
        self.write_char('"')?;
        Ok(())
    }
    
    /// Format a character value.
    fn format_char(&mut self, c: char) -> RsonResult<()> {
        self.write_char('\'')?;
        match c {
            '\'' => self.write_str("\\'")?,
            '\\' => self.write_str("\\\\")?,
            '\n' => self.write_str("\\n")?,
            '\r' => self.write_str("\\r")?,
            '\t' => self.write_str("\\t")?,
            '\0' => self.write_str("\\0")?,
            c if c.is_control() => {
                write!(self.output, "\\u{:04x}", c as u32)
                    .map_err(|_| RsonError::custom("Failed to write Unicode escape"))?;
            }
            c => self.write_char(c)?,
        }
        self.write_char('\'')?;
        Ok(())
    }
    
    /// Format an array.
    fn format_array(&mut self, arr: &[RsonValue]) -> RsonResult<()> {
        self.write_char('[')?;
        
        if arr.is_empty() {
            self.write_char(']')?;
            return Ok(());
        }
        
        let multiline = !self.options.compact && self.should_be_multiline_array(arr);
        
        if multiline {
            self.write_newline()?;
            self.indent_level += 1;
        }
        
        for (i, item) in arr.iter().enumerate() {
            if i > 0 {
                self.write_char(',')?;
                if multiline {
                    self.write_newline()?;
                } else {
                    self.write_space()?;
                }
            }
            
            if multiline {
                self.write_indent()?;
            }
            
            self.format_value(item)?;
        }
        
        if self.options.trailing_commas && !arr.is_empty() {
            self.write_char(',')?;
        }
        
        if multiline {
            self.write_newline()?;
            self.indent_level -= 1;
            self.write_indent()?;
        }
        
        self.write_char(']')?;
        Ok(())
    }
    
    /// Format a map.
    fn format_map(&mut self, map: &indexmap::IndexMap<String, RsonValue>) -> RsonResult<()> {
        self.write_char('{')?;
        
        if map.is_empty() {
            self.write_char('}')?;
            return Ok(());
        }
        
        let multiline = !self.options.compact && self.should_be_multiline_map(map);
        
        if multiline {
            self.write_newline()?;
            self.indent_level += 1;
        }
        
        let mut entries: Vec<_> = map.iter().collect();
        if self.options.sort_keys {
            entries.sort_by_key(|(key, _)| *key);
        }
        
        for (i, (key, value)) in entries.iter().enumerate() {
            if i > 0 {
                self.write_char(',')?;
                if multiline {
                    self.write_newline()?;
                } else {
                    self.write_space()?;
                }
            }
            
            if multiline {
                self.write_indent()?;
            }
            
            self.format_map_key(key)?;
            self.write_char(':')?;
            self.write_space()?;
            self.format_value(value)?;
        }
        
        if self.options.trailing_commas && !map.is_empty() {
            self.write_char(',')?;
        }
        
        if multiline {
            self.write_newline()?;
            self.indent_level -= 1;
            self.write_indent()?;
        }
        
        self.write_char('}')?;
        Ok(())
    }
    
    /// Format a map key (quoted if necessary).
    fn format_map_key(&mut self, key: &str) -> RsonResult<()> {
        if is_valid_identifier(key) {
            self.write_str(key)?;
        } else {
            self.format_string(key)?;
        }
        Ok(())
    }
    
    /// Format a struct.
    fn format_struct(&mut self, name: &str, fields: &indexmap::IndexMap<String, RsonValue>) -> RsonResult<()> {
        self.write_str(name)?;
        self.write_char('(')?;
        
        if fields.is_empty() {
            self.write_char(')')?;
            return Ok(());
        }
        
        let multiline = !self.options.compact && self.should_be_multiline_struct(fields);
        
        if multiline {
            self.write_newline()?;
            self.indent_level += 1;
        }
        
        for (i, (field_name, value)) in fields.iter().enumerate() {
            if i > 0 {
                self.write_char(',')?;
                if multiline {
                    self.write_newline()?;
                } else {
                    self.write_space()?;
                }
            }
            
            if multiline {
                self.write_indent()?;
            }
            
            self.write_str(field_name)?;
            self.write_char(':')?;
            self.write_space()?;
            self.format_value(value)?;
        }
        
        if self.options.trailing_commas && !fields.is_empty() {
            self.write_char(',')?;
        }
        
        if multiline {
            self.write_newline()?;
            self.indent_level -= 1;
            self.write_indent()?;
        }
        
        self.write_char(')')?;
        Ok(())
    }
    
    /// Format a tuple.
    fn format_tuple(&mut self, values: &[RsonValue]) -> RsonResult<()> {
        self.write_char('(')?;
        
        for (i, value) in values.iter().enumerate() {
            if i > 0 {
                self.write_char(',')?;
                self.write_space()?;
            }
            self.format_value(value)?;
        }
        
        // Always add trailing comma for single-element tuples to distinguish from parentheses
        if values.len() == 1 || (self.options.trailing_commas && !values.is_empty()) {
            self.write_char(',')?;
        }
        
        self.write_char(')')?;
        Ok(())
    }
    
    /// Format an enum.
    fn format_enum(&mut self, name: &str, variant: &str, value: Option<&RsonValue>) -> RsonResult<()> {
        self.write_str(name)?;
        self.write_str("::")?;
        self.write_str(variant)?;
        
        if let Some(val) = value {
            self.write_char('(')?;
            self.format_value(val)?;
            self.write_char(')')?;
        }
        
        Ok(())
    }
    
    /// Format an Option.
    fn format_option(&mut self, value: Option<&RsonValue>) -> RsonResult<()> {
        match value {
            Some(val) => {
                self.write_str("Some(")?;
                self.format_value(val)?;
                self.write_char(')')?;
            }
            None => self.write_str("None")?,
        }
        Ok(())
    }
    
    /// Check if an array should be formatted as multiline.
    fn should_be_multiline_array(&self, arr: &[RsonValue]) -> bool {
        if self.options.compact {
            return false;
        }
        
        // Simple heuristic: multiline if more than 3 elements or contains complex structures
        arr.len() > 3 || arr.iter().any(|v| matches!(v, 
            RsonValue::Array(_) | 
            RsonValue::Map(_) | 
            RsonValue::Struct { .. }
        ))
    }
    
    /// Check if a map should be formatted as multiline.
    fn should_be_multiline_map(&self, map: &indexmap::IndexMap<String, RsonValue>) -> bool {
        if self.options.compact {
            return false;
        }
        
        // Multiline if more than 1 field or contains complex structures
        map.len() > 1 || map.values().any(|v| matches!(v,
            RsonValue::Array(_) | 
            RsonValue::Map(_) | 
            RsonValue::Struct { .. }
        ))
    }
    
    /// Check if a struct should be formatted as multiline.
    fn should_be_multiline_struct(&self, fields: &indexmap::IndexMap<String, RsonValue>) -> bool {
        if self.options.compact {
            return false;
        }
        
        // Multiline if more than 2 fields or contains complex structures
        fields.len() > 2 || fields.values().any(|v| matches!(v,
            RsonValue::Array(_) | 
            RsonValue::Map(_) | 
            RsonValue::Struct { .. }
        ))
    }
}

/// Check if a string is a valid identifier (can be unquoted).
fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    
    // Check if it's a reserved keyword
    match s {
        "true" | "false" | "null" | "Some" | "None" => return false,
        _ => {}
    }
    
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    
    // First character must be letter or underscore
    if !first.is_alphabetic() && first != '_' {
        return false;
    }
    
    // Remaining characters must be alphanumeric or underscore
    chars.all(|c| c.is_alphanumeric() || c == '_')
}

/// Format an RSON value with the given options.
pub fn format_rson(value: &RsonValue, options: &FormatOptions) -> RsonResult<String> {
    let formatter = Formatter::new(options);
    formatter.format(value)
}

/// Format an RSON value with default pretty formatting.
pub fn format_pretty(value: &RsonValue) -> RsonResult<String> {
    format_rson(value, &FormatOptions::pretty())
}

/// Format an RSON value with compact formatting.
pub fn format_compact(value: &RsonValue) -> RsonResult<String> {
    format_rson(value, &FormatOptions::compact())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::RsonValue;
    use indexmap::IndexMap;

    #[test]
    fn test_format_primitives() {
        assert_eq!(format_compact(&RsonValue::Null).unwrap(), "null");
        assert_eq!(format_compact(&RsonValue::Bool(true)).unwrap(), "true");
        assert_eq!(format_compact(&RsonValue::Bool(false)).unwrap(), "false");
        assert_eq!(format_compact(&RsonValue::Int(42)).unwrap(), "42");
        assert_eq!(format_compact(&RsonValue::Float(3.14)).unwrap(), "3.14");
        assert_eq!(format_compact(&RsonValue::String("hello".to_string())).unwrap(), r#""hello""#);
        assert_eq!(format_compact(&RsonValue::Char('a')).unwrap(), "'a'");
    }

    #[test]
    fn test_format_array() {
        let arr = RsonValue::Array(vec![
            RsonValue::Int(1),
            RsonValue::Int(2),
            RsonValue::Int(3),
        ]);
        
        assert_eq!(format_compact(&arr).unwrap(), "[1,2,3]");
        
        let pretty = format_pretty(&arr).unwrap();
        assert!(pretty.contains("["));
        assert!(pretty.contains("1,"));
        assert!(pretty.contains("2,"));
        assert!(pretty.contains("3,"));
        assert!(pretty.contains("]"));
    }

    #[test]
    fn test_format_map() {
        let mut map = IndexMap::new();
        map.insert("name".to_string(), RsonValue::String("Alice".to_string()));
        map.insert("age".to_string(), RsonValue::Int(30));
        
        let value = RsonValue::Map(map);
        let formatted = format_compact(&value).unwrap();
        
        assert!(formatted.contains("name:\"Alice\""));
        assert!(formatted.contains("age:30"));
    }

    #[test]
    fn test_format_struct() {
        let mut fields = IndexMap::new();
        fields.insert("x".to_string(), RsonValue::Int(10));
        fields.insert("y".to_string(), RsonValue::Int(20));
        
        let value = RsonValue::Struct {
            name: "Point".to_string(),
            fields,
        };
        
        let formatted = format_compact(&value).unwrap();
        assert_eq!(formatted, "Point(x:10,y:20)");
    }

    #[test]
    fn test_format_enum() {
        let enum_val = RsonValue::Enum {
            name: "Color".to_string(),
            variant: "Red".to_string(),
            value: None,
        };
        
        assert_eq!(format_compact(&enum_val).unwrap(), "Color::Red");
        
        let enum_with_value = RsonValue::Enum {
            name: "Result".to_string(),
            variant: "Ok".to_string(),
            value: Some(Box::new(RsonValue::String("success".to_string()))),
        };
        
        assert_eq!(format_compact(&enum_with_value).unwrap(), r#"Result::Ok("success")"#);
    }

    #[test]
    fn test_format_option() {
        assert_eq!(format_compact(&RsonValue::Option(None)).unwrap(), "None");
        assert_eq!(
            format_compact(&RsonValue::Option(Some(Box::new(RsonValue::Int(42))))).unwrap(),
            "Some(42)"
        );
    }

    #[test]
    fn test_string_escaping() {
        let value = RsonValue::String("hello\nworld\"test".to_string());
        let formatted = format_compact(&value).unwrap();
        assert_eq!(formatted, r#""hello\nworld\"test""#);
    }

    #[test]
    fn test_identifier_validation() {
        assert!(is_valid_identifier("hello"));
        assert!(is_valid_identifier("_private"));
        assert!(is_valid_identifier("field1"));
        assert!(!is_valid_identifier("123invalid"));
        assert!(!is_valid_identifier("true"));
        assert!(!is_valid_identifier(""));
        assert!(!is_valid_identifier("hello-world"));
    }
}