toonconv 0.1.0

A Rust CLI tool for converting JSON to TOON (Token-Oriented Object Notation) format
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
//! TOON output compliance validation
//!
//! Validates that generated TOON output conforms to the TOON specification
//! and maintains data integrity from the original JSON.

use crate::error::{FormattingError, FormattingResult};
use serde_json::Value;

/// TOON compliance validator
pub struct ToonValidator {
    /// Enable strict validation mode
    strict: bool,
}

impl ToonValidator {
    /// Create a new TOON validator
    pub fn new(strict: bool) -> Self {
        Self { strict }
    }

    /// Validate TOON output compliance
    pub fn validate(
        &self,
        toon_output: &str,
        original_json: &Value,
    ) -> FormattingResult<ValidationReport> {
        let mut report = ValidationReport::new();

        // Basic structural validation
        self.validate_structure(toon_output, &mut report)?;

        // Bracket balance validation
        self.validate_brackets(toon_output, &mut report)?;

        // Content validation (data integrity)
        self.validate_content(toon_output, original_json, &mut report)?;

        // Character encoding validation
        self.validate_encoding(toon_output, &mut report)?;

        // Formatting consistency validation
        self.validate_formatting(toon_output, &mut report)?;

        if self.strict && !report.is_valid() {
            return Err(FormattingError::invalid_structure(format!(
                "TOON validation failed: {:?}",
                report.issues
            )));
        }

        Ok(report)
    }

    /// Validate basic structure
    fn validate_structure(
        &self,
        output: &str,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        // Note: Empty string is valid for empty objects per TOON spec
        // Don't treat empty output as an error

        // Check for valid UTF-8
        if !output.is_char_boundary(0) || !output.is_char_boundary(output.len()) {
            report.add_error("Output contains invalid UTF-8");
        }

        report.structure_valid = true;
        Ok(())
    }

    /// Validate bracket balancing
    fn validate_brackets(
        &self,
        output: &str,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        let mut brace_stack = Vec::new();
        let mut bracket_stack = Vec::new();
        let mut in_string = false;
        let mut escape_next = false;

        for (i, ch) in output.chars().enumerate() {
            // Handle string context
            if escape_next {
                escape_next = false;
                continue;
            }

            if ch == '\\' {
                escape_next = true;
                continue;
            }

            if ch == '"' {
                in_string = !in_string;
                continue;
            }

            if in_string {
                continue;
            }

            // Track brackets outside strings
            match ch {
                '{' => brace_stack.push(i),
                '}' => {
                    if brace_stack.pop().is_none() {
                        report.add_error(&format!("Unmatched closing brace at position {}", i));
                    }
                }
                '[' => bracket_stack.push(i),
                ']' => {
                    if bracket_stack.pop().is_none() {
                        report.add_error(&format!("Unmatched closing bracket at position {}", i));
                    }
                }
                _ => {}
            }
        }

        // Check for unclosed brackets
        if !brace_stack.is_empty() {
            report.add_error(&format!("{} unclosed braces", brace_stack.len()));
        }

        if !bracket_stack.is_empty() {
            report.add_error(&format!("{} unclosed brackets", bracket_stack.len()));
        }

        report.brackets_balanced = brace_stack.is_empty() && bracket_stack.is_empty();
        Ok(())
    }

    /// Validate content integrity
    fn validate_content(
        &self,
        output: &str,
        original: &Value,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        // Extract key values from JSON
        let json_values = self.extract_values(original);

        // Check if critical values are present in output
        let mut missing_values = Vec::new();
        for value in &json_values {
            if !self.value_present_in_output(value, output) {
                missing_values.push(value.clone());
            }
        }

        if !missing_values.is_empty() {
            report.add_warning(&format!("{} values may be missing", missing_values.len()));
        }

        report.data_integrity = missing_values.is_empty();
        Ok(())
    }

    /// Extract values from JSON for validation
    fn extract_values(&self, json: &Value) -> Vec<String> {
        let mut values = Vec::new();
        Self::extract_values_recursive(json, &mut values);
        values
    }

    /// Extract values iteratively using an explicit stack to prevent stack overflow
    fn extract_values_recursive(json: &Value, values: &mut Vec<String>) {
        let mut stack = vec![json];

        while let Some(current) = stack.pop() {
            match current {
                Value::Null => values.push("null".to_string()),
                Value::Bool(b) => values.push(b.to_string()),
                Value::Number(n) => values.push(n.to_string()),
                Value::String(s) => values.push(s.clone()),
                Value::Array(arr) => {
                    for item in arr.iter().rev() {
                        stack.push(item);
                    }
                }
                Value::Object(obj) => {
                    for (key, value) in obj.iter().rev() {
                        values.push(key.clone());
                        stack.push(value);
                    }
                }
            }
        }
    }

    /// Check if value is present in output
    fn value_present_in_output(&self, value: &str, output: &str) -> bool {
        // Simple substring check - could be made more sophisticated
        output.contains(value)
            || output.contains(&format!("\"{}\"", value))
            || output.contains(&self.escape_string(value))
    }

    /// Escape string for comparison
    fn escape_string(&self, s: &str) -> String {
        s.replace('"', "\\\"")
            .replace('\n', "\\n")
            .replace('\r', "\\r")
            .replace('\t', "\\t")
    }

    /// Validate character encoding
    fn validate_encoding(
        &self,
        output: &str,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        // Check for valid UTF-8 (should already be validated)
        if output.is_empty() {
            return Ok(());
        }

        // Check for control characters that should be escaped
        for (i, ch) in output.char_indices() {
            if ch.is_control() && !matches!(ch, '\n' | '\r' | '\t') {
                // Control characters should be escaped
                if !output[..i].ends_with('\\') {
                    report.add_warning(&format!("Unescaped control character at position {}", i));
                }
            }
        }

        report.encoding_valid = true;
        Ok(())
    }

    /// Validate formatting consistency
    fn validate_formatting(
        &self,
        output: &str,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        // Check for consistent indentation (if pretty-printed)
        if output.contains('\n') {
            self.validate_indentation(output, report)?;
        }

        // Check for proper delimiter usage
        self.validate_delimiters(output, report)?;

        report.formatting_consistent = true;
        Ok(())
    }

    /// Validate indentation consistency
    fn validate_indentation(
        &self,
        output: &str,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        let lines: Vec<&str> = output.lines().collect();

        for (i, line) in lines.iter().enumerate() {
            if line.is_empty() {
                continue;
            }

            // Count leading spaces
            let leading_spaces = line.chars().take_while(|c| *c == ' ').count();

            // Check if indentation is consistent (multiple of some indent size)
            if leading_spaces > 0 && leading_spaces % 2 != 0 && leading_spaces % 4 != 0 {
                report.add_warning(&format!(
                    "Inconsistent indentation on line {}: {} spaces",
                    i + 1,
                    leading_spaces
                ));
            }
        }

        Ok(())
    }

    /// Validate delimiter usage
    fn validate_delimiters(
        &self,
        output: &str,
        report: &mut ValidationReport,
    ) -> FormattingResult<()> {
        // Check for proper colon usage (key:value)
        // This is a basic check - could be more sophisticated
        let colon_count = output.matches(':').count();

        if colon_count == 0 && output.contains('{') {
            report.add_warning("Object detected but no colons found");
        }

        Ok(())
    }
}

/// Validation report
#[derive(Debug, Clone, Default)]
pub struct ValidationReport {
    /// Is structure valid
    pub structure_valid: bool,

    /// Are brackets balanced
    pub brackets_balanced: bool,

    /// Is data integrity maintained
    pub data_integrity: bool,

    /// Is encoding valid
    pub encoding_valid: bool,

    /// Is formatting consistent
    pub formatting_consistent: bool,

    /// List of validation issues
    pub issues: Vec<ValidationIssue>,
}

impl ValidationReport {
    /// Create a new validation report
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an error to the report
    pub fn add_error(&mut self, message: &str) {
        self.issues.push(ValidationIssue {
            severity: IssueSeverity::Error,
            message: message.to_string(),
        });
    }

    /// Add a warning to the report
    pub fn add_warning(&mut self, message: &str) {
        self.issues.push(ValidationIssue {
            severity: IssueSeverity::Warning,
            message: message.to_string(),
        });
    }

    /// Check if validation passed (no errors)
    pub fn is_valid(&self) -> bool {
        !self
            .issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Error)
    }

    /// Get error count
    pub fn error_count(&self) -> usize {
        self.issues
            .iter()
            .filter(|i| i.severity == IssueSeverity::Error)
            .count()
    }

    /// Get warning count
    pub fn warning_count(&self) -> usize {
        self.issues
            .iter()
            .filter(|i| i.severity == IssueSeverity::Warning)
            .count()
    }
}

/// Validation issue
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    pub severity: IssueSeverity,
    pub message: String,
}

/// Issue severity
#[derive(Debug, Clone, PartialEq)]
pub enum IssueSeverity {
    Error,
    Warning,
}

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

    #[test]
    fn test_valid_toon_output() {
        let validator = ToonValidator::new(false);
        let json = json!({"name": "Alice", "age": 30});
        let toon = "{name: Alice, age: 30}";

        let report = validator.validate(toon, &json).unwrap();
        assert!(report.structure_valid);
        assert!(report.brackets_balanced);
    }

    #[test]
    fn test_empty_output_validation() {
        // Empty output is valid for empty objects per TOON spec
        let validator = ToonValidator::new(false);
        let json = json!({});

        let report = validator.validate("", &json).unwrap();
        // Empty output is now valid, so no errors
        assert_eq!(report.error_count(), 0);
    }

    #[test]
    fn test_unbalanced_brackets() {
        let validator = ToonValidator::new(false);
        let json = json!({"test": "value"});
        let toon = "{name: Alice"; // Missing closing brace

        let report = validator.validate(toon, &json).unwrap();
        assert!(!report.brackets_balanced);
        assert!(report.error_count() > 0);
    }

    #[test]
    fn test_bracket_in_string_ignored() {
        let validator = ToonValidator::new(false);
        let json = json!({"data": "{not a bracket}"});
        let toon = r#"{data: "{not a bracket}"}"#;

        let report = validator.validate(toon, &json).unwrap();
        assert!(report.brackets_balanced);
    }

    #[test]
    fn test_data_integrity_check() {
        let validator = ToonValidator::new(false);
        let json = json!({"name": "Alice", "age": 30, "city": "NYC"});
        let toon = "{name: Alice, age: 30}"; // Missing city

        let report = validator.validate(toon, &json).unwrap();
        assert!(!report.data_integrity);
    }

    #[test]
    fn test_complete_data_integrity() {
        let validator = ToonValidator::new(false);
        let json = json!({"name": "Alice", "value": 42});
        let toon = "{name: Alice, value: 42}";

        let report = validator.validate(toon, &json).unwrap();
        assert!(report.data_integrity);
    }

    #[test]
    fn test_escaped_quotes_in_strings() {
        let validator = ToonValidator::new(false);
        let json = json!({"message": "Hello \"World\""});
        let toon = r#"{message: "Hello \"World\""}"#;

        let report = validator.validate(toon, &json).unwrap();
        assert!(report.structure_valid);
    }

    #[test]
    fn test_strict_mode_failure() {
        let validator = ToonValidator::new(true);
        let json = json!({"test": "value"});
        let toon = "{test: value"; // Unbalanced

        let result = validator.validate(toon, &json);
        assert!(result.is_err());
    }

    #[test]
    fn test_non_strict_mode_with_warnings() {
        let validator = ToonValidator::new(false);
        let json = json!({"test": "value"});
        let toon = "{test: value"; // Unbalanced

        let report = validator.validate(toon, &json).unwrap();
        assert!(!report.is_valid()); // Has errors
        assert!(report.error_count() > 0);
    }

    #[test]
    fn test_indentation_validation() {
        let validator = ToonValidator::new(false);
        let json = json!({"outer": {"inner": "value"}});
        let toon = "{\n  outer: {\n    inner: value\n  }\n}";

        let report = validator.validate(toon, &json).unwrap();
        assert!(report.formatting_consistent);
    }

    #[test]
    fn test_nested_structures_validation() {
        let validator = ToonValidator::new(false);
        let json = json!({
            "user": {
                "name": "Alice",
                "scores": [95, 87, 92]
            }
        });
        let toon = "{user: {name: Alice, scores: [95, 87, 92]}}";

        let report = validator.validate(toon, &json).unwrap();
        assert!(report.structure_valid);
        assert!(report.brackets_balanced);
    }
}