jsonette-core 0.4.0

JSON parse, format, query, and diagnostics engine — core library for the jsonette tool
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
/*
 * Copyright (c) 2026 DevEtte.
 *
 * This project is dual-licensed under both the MIT License and the
 * Apache License, Version 2.0 (the "License"). You may not use this
 * file except in compliance with one of these licenses.
 *
 * You may obtain a copy of the Licenses at:
 * - MIT: https://opensource.org
 * - Apache 2.0: http://apache.org
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! Strict JSON parser implementation carrying byte-accurate spans for AST nodes.

use crate::json_node::{JsonNode, KeyValuePair};
use crate::types::{Diagnostic, Span};

macro_rules! t_err {
    ($self:expr, $pos:expr, $msg:expr $(,)?) => {{
        let d = $self.error($pos, $msg);
        $self.diagnostics.push(d);
    }};
}

/// Tolerant parsing: Fails entirely if the JSON is invalid.
/// Returns the parsed tree or a list of diagnostic errors.
/// Primarily used for final validation.
///
/// # Arguments
///
/// * `input` - The raw JSON string slice to parse.
///
/// # Returns
///
/// * `Some(JsonNode)` - The parsed JSON abstract syntax tree (AST) on successful parse.
/// * `Err(Vec<Diagnostic>)` - A list of syntax or structural errors found during parsing.
pub fn parse(input: &str) -> (Option<JsonNode>, Vec<Diagnostic>) {
    let mut parser = Parser::new(input);
    let node = parser.parse_value();
    parser.skip_whitespace();
    if parser.cursor < parser.input.len() {
        let err = parser.error(
            parser.cursor,
            "Unexpected trailing characters after JSON value",
        );
        parser.diagnostics.push(err);
    }
    (node, parser.diagnostics)
}

struct Parser<'a> {
    pub diagnostics: Vec<Diagnostic>,
    /// The input bytes slice of the JSON document.
    input: &'a [u8],
    /// The original input string slice for number parsing and error reporting.
    input_str: &'a str,
    /// The current byte offset cursor in the input.
    cursor: usize,
}

impl<'a> Parser<'a> {
    /// Creates a new Parser instance for the given JSON input.
    fn new(input: &'a str) -> Self {
        Parser {
            input: input.as_bytes(),
            input_str: input,
            cursor: 0,
            diagnostics: Vec::new(),
        }
    }

    /// Returns the character byte at the current cursor, or `None` if EOF is reached.
    fn peek(&self) -> Option<u8> {
        if self.cursor < self.input.len() {
            Some(self.input[self.cursor])
        } else {
            None
        }
    }

    /// Returns the character byte at one position ahead of the current cursor, or `None` if EOF is reached.
    fn peek_next(&self) -> Option<u8> {
        if self.cursor + 1 < self.input.len() {
            Some(self.input[self.cursor + 1])
        } else {
            None
        }
    }

    /// Advances the cursor by one byte.
    fn advance(&mut self) {
        if self.cursor < self.input.len() {
            self.cursor += 1;
        }
    }

    /// Skips any ASCII whitespace characters (spaces, tabs, newlines, carriage returns)
    /// and single-line/multi-line comments if they are allowed in configuration.
    fn skip_whitespace(&mut self) {
        let allow_comments = false; // crate::settings::get_settings().parser.allow_comments;
        loop {
            let start = self.cursor;
            // 1. Skip standard whitespace
            while let Some(b) = self.peek() {
                if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
                    self.advance();
                } else {
                    break;
                }
            }
            // 2. Skip comments if enabled
            if allow_comments && self.peek() == Some(b'/') {
                match self.peek_next() {
                    Some(b'/') => {
                        // Line comment: skip until newline or EOF
                        self.advance(); // skip '/'
                        self.advance(); // skip '/'
                        while let Some(c) = self.peek() {
                            if c == b'\n' {
                                self.advance();
                                break;
                            }
                            self.advance();
                        }
                        continue;
                    }
                    Some(b'*') => {
                        // Block comment: skip until '*/' or EOF
                        self.advance(); // skip '/'
                        self.advance(); // skip '*'
                        while let Some(c) = self.peek() {
                            if c == b'*' && self.peek_next() == Some(b'/') {
                                self.advance(); // skip '*'
                                self.advance(); // skip '/'
                                break;
                            }
                            self.advance();
                        }
                        continue;
                    }
                    _ => {}
                }
            }

            if self.cursor == start {
                break;
            }
        }
    }

    /// Helper to create a single-character `Diagnostic` error starting at the given position.
    fn error(&self, pos: usize, message: impl Into<String>) -> Diagnostic {
        let end = (pos + 1).min(self.input.len());
        Diagnostic {
            span: Span { start: pos, end },
            message: message.into(),
        }
    }

    /// Main entry point to parse a JSON value (null, bool, number, string, array, object).
    fn parse_value(&mut self) -> Option<JsonNode> {
        self.skip_whitespace();
        let start = self.cursor;
        let b = match self.peek() {
            Some(b) => b,
            None => {
                return {
                    t_err!(self, start, "Unexpected end of input");
                    None
                };
            }
        };

        match b {
            b'n' => self.parse_null(),
            b't' | b'f' => self.parse_bool(),
            b'"' => self.parse_string_node(),
            b'[' => self.parse_array(),
            b'{' => self.parse_object(),
            b'-' | b'0'..=b'9' => self.parse_number(),
            _ => {
                t_err!(self, start, format!("Unexpected character '{}'", b as char));
                None
            }
        }
    }

    /// Parses a JSON null value.
    fn parse_null(&mut self) -> Option<JsonNode> {
        let start = self.cursor;
        if self.cursor + 4 <= self.input.len()
            && &self.input[self.cursor..self.cursor + 4] == b"null"
        {
            self.cursor += 4;
            Some(JsonNode::Null(Span {
                start,
                end: self.cursor,
            }))
        } else {
            {
                t_err!(self, start, "Expected 'null'");
                None
            }
        }
    }

    /// Parses a JSON boolean value (true or false).
    fn parse_bool(&mut self) -> Option<JsonNode> {
        let start = self.cursor;
        if self.cursor + 4 <= self.input.len()
            && &self.input[self.cursor..self.cursor + 4] == b"true"
        {
            self.cursor += 4;
            Some(JsonNode::Bool(
                true,
                Span {
                    start,
                    end: self.cursor,
                },
            ))
        } else if self.cursor + 5 <= self.input.len()
            && &self.input[self.cursor..self.cursor + 5] == b"false"
        {
            self.cursor += 5;
            Some(JsonNode::Bool(
                false,
                Span {
                    start,
                    end: self.cursor,
                },
            ))
        } else {
            {
                t_err!(self, start, "Expected boolean value");
                None
            }
        }
    }

    /// Parses a raw string value, decoding escape characters and surrogate pairs,
    /// and returns the decoded string and its source span.
    fn parse_string_raw(&mut self) -> Option<(String, Span)> {
        let start = self.cursor;
        if self.peek() != Some(b'"') {
            return {
                t_err!(self, start, "Expected opening quote for string");
                None
            };
        }
        self.advance(); // consume opening quote

        let mut s = String::new();
        while let Some(b) = self.peek() {
            match b {
                b'"' => {
                    self.advance(); // consume closing quote
                    return Some((
                        s,
                        Span {
                            start,
                            end: self.cursor,
                        },
                    ));
                }
                b'\\' => {
                    self.advance(); // consume backslash
                    let esc = match self.peek() {
                        Some(esc) => esc,
                        None => {
                            return {
                                t_err!(self, self.cursor, "Unterminated string escape");
                                None
                            };
                        }
                    };
                    self.advance(); // consume escape char
                    match esc {
                        b'"' => s.push('"'),
                        b'\\' => s.push('\\'),
                        b'/' => s.push('/'),
                        b'b' => s.push('\x08'),
                        b'f' => s.push('\x0c'),
                        b'n' => s.push('\n'),
                        b'r' => s.push('\r'),
                        b't' => s.push('\t'),
                        b'u' => {
                            if self.cursor + 4 > self.input.len() {
                                return {
                                    t_err!(self, self.cursor, "Invalid unicode escape sequence");
                                    None
                                };
                            }
                            let hex_str =
                                std::str::from_utf8(&self.input[self.cursor..self.cursor + 4])
                                    .map_err(|_| {
                                        let err = self
                                            .error(self.cursor, "Invalid utf-8 in unicode escape");
                                        self.diagnostics.push(err);
                                    })
                                    .ok()?;
                            let code_point = u16::from_str_radix(hex_str, 16)
                                .map_err(|_| {
                                    let err =
                                        self.error(self.cursor, "Invalid hex in unicode escape");
                                    self.diagnostics.push(err);
                                })
                                .ok()?;
                            self.cursor += 4;

                            if (0xD800..=0xDBFF).contains(&code_point) {
                                if self.cursor + 6 <= self.input.len()
                                    && &self.input[self.cursor..self.cursor + 2] == b"\\u"
                                {
                                    self.cursor += 2;
                                    let low_hex_str = std::str::from_utf8(
                                        &self.input[self.cursor..self.cursor + 4],
                                    )
                                    .map_err(|_| {
                                        let err = self
                                            .error(self.cursor, "Invalid utf-8 in low surrogate");
                                        self.diagnostics.push(err);
                                    })
                                    .ok()?;
                                    let low_code_point = u16::from_str_radix(low_hex_str, 16)
                                        .map_err(|_| {
                                            let err = self
                                                .error(self.cursor, "Invalid hex in low surrogate");
                                            self.diagnostics.push(err);
                                        })
                                        .ok()?;
                                    self.cursor += 4;
                                    if (0xDC00..=0xDFFF).contains(&low_code_point) {
                                        let utf32 = (((code_point - 0xD800) as u32) << 10)
                                            + (low_code_point - 0xDC00) as u32
                                            + 0x10000;
                                        if let Some(c) = std::char::from_u32(utf32) {
                                            s.push(c);
                                        } else {
                                            return {
                                                t_err!(
                                                    self,
                                                    self.cursor - 12,
                                                    "Invalid surrogate pair",
                                                );
                                                None
                                            };
                                        }
                                    } else {
                                        return {
                                            t_err!(
                                                self,
                                                self.cursor - 6,
                                                "Expected low surrogate after high surrogate",
                                            );
                                            None
                                        };
                                    }
                                } else {
                                    return {
                                        t_err!(
                                            self,
                                            self.cursor,
                                            "Expected low surrogate after high surrogate",
                                        );
                                        None
                                    };
                                }
                            } else if (0xDC00..=0xDFFF).contains(&code_point) {
                                return {
                                    t_err!(
                                        self,
                                        self.cursor - 6,
                                        "Unexpected low surrogate without high surrogate",
                                    );
                                    None
                                };
                            } else {
                                if let Some(c) = std::char::from_u32(code_point as u32) {
                                    s.push(c);
                                } else {
                                    return {
                                        t_err!(self, self.cursor - 6, "Invalid unicode code point");
                                        None
                                    };
                                }
                            }
                        }
                        _ => {
                            return {
                                t_err!(
                                    self,
                                    self.cursor - 1,
                                    format!("Invalid escape character '{}'", esc as char),
                                );
                                None
                            };
                        }
                    }
                }
                b @ 0..=0x1f => {
                    return {
                        t_err!(self, self.cursor, "Control characters must be escaped");
                        None
                    };
                }
                _ => {
                    let tail = &self.input_str[self.cursor..];
                    let c = match tail.chars().next() {
                        Some(ch) => ch,
                        None => {
                            return {
                                t_err!(self, self.cursor, "Unexpected EOF");
                                None
                            };
                        }
                    };
                    self.cursor += c.len_utf8();
                    s.push(c);
                }
            }
        }
        {
            t_err!(self, start, "Unterminated string");
            Some((
                s,
                Span {
                    start,
                    end: self.cursor,
                },
            ))
        }
    }

    /// Parses a JSON string value.
    fn parse_string_node(&mut self) -> Option<JsonNode> {
        let (s, span) = self.parse_string_raw()?;
        Some(JsonNode::String(s, span))
    }

    /// Parses a JSON number value.
    fn parse_number(&mut self) -> Option<JsonNode> {
        let start = self.cursor;

        if self.peek() == Some(b'-') {
            self.advance();
        }

        match self.peek() {
            Some(b'0') => {
                self.advance();
            }
            Some(b) if b.is_ascii_digit() => {
                while let Some(next_b) = self.peek() {
                    if next_b.is_ascii_digit() {
                        self.advance();
                    } else {
                        break;
                    }
                }
            }
            _ => {
                return {
                    t_err!(self, start, "Expected digit for number");
                    None
                };
            }
        }

        if self.peek() == Some(b'.') {
            self.advance();
            while let Some(next_b) = self.peek() {
                if next_b.is_ascii_digit() {
                    self.advance();
                } else {
                    break;
                }
            }
        }

        if let Some(b'e' | b'E') = self.peek() {
            self.advance();
            if let Some(b'+' | b'-') = self.peek() {
                self.advance();
            }
            while let Some(next_b) = self.peek() {
                if next_b.is_ascii_digit() {
                    self.advance();
                } else {
                    break;
                }
            }
        }

        let end = self.cursor;
        let span = Span { start, end };
        let raw_str = self.input_str[start..end].to_string();

        let val: f64 = raw_str.parse().unwrap_or(0.0);

        Some(JsonNode::Number(val, raw_str, span))
    }

    /// Parses a JSON array value.
    fn parse_array(&mut self) -> Option<JsonNode> {
        let start = self.cursor;
        if self.peek() != Some(b'[') {
            {
                t_err!(self, start, "Expected '['");
                return None;
            }
        }
        self.advance(); // consume '['

        self.skip_whitespace();
        if self.peek() == Some(b']') {
            self.advance(); // consume ']'
            return Some(JsonNode::Array(
                vec![],
                Span {
                    start,
                    end: self.cursor,
                },
            ));
        }

        let mut elements = Vec::new();
        #[allow(clippy::while_let_loop)]
        loop {
            let val = if let Some(v) = self.parse_value() {
                v
            } else {
                break;
            };
            elements.push(val);

            self.skip_whitespace();
            match self.peek() {
                Some(b',') => {
                    self.advance();
                    self.skip_whitespace();
                    if self.peek() == Some(b']') {
                        if !crate::settings::get_settings().parser.allow_trailing_commas {
                            t_err!(self, self.cursor, "Trailing commas are not allowed in JSON");
                        }
                        self.advance();
                        break;
                    }
                }
                Some(b']') => {
                    self.advance();
                    break;
                }
                Some(b) => {
                    t_err!(
                        self,
                        self.cursor,
                        format!(
                            "Expected ',' or ']' after array element, found '{}'",
                            b as char
                        )
                    );
                    break;
                }
                None => {
                    t_err!(self, self.cursor, "Unterminated array");
                    break;
                }
            }
        }

        Some(JsonNode::Array(
            elements,
            Span {
                start,
                end: self.cursor,
            },
        ))
    }

    /// Parses a JSON object value.
    fn parse_object(&mut self) -> Option<JsonNode> {
        let start = self.cursor;
        if self.peek() != Some(b'{') {
            {
                t_err!(self, start, "Expected '{'");
                return None;
            }
        }
        self.advance(); // consume '{'

        self.skip_whitespace();
        if self.peek() == Some(b'}') {
            self.advance(); // consume '}'
            return Some(JsonNode::Object(
                vec![],
                Span {
                    start,
                    end: self.cursor,
                },
            ));
        }

        let mut pairs = Vec::new();
        #[allow(clippy::while_let_loop)]
        loop {
            self.skip_whitespace();
            let key_start = self.cursor;
            if self.peek() != Some(b'"') {
                {
                    t_err!(self, key_start, "Expected string key in object");
                    break;
                }
            }
            let (key, _) = if let Some(k) = self.parse_string_raw() {
                k
            } else {
                break;
            };

            self.skip_whitespace();
            let colon_pos = self.cursor;
            if self.peek() != Some(b':') {
                {
                    t_err!(self, colon_pos, "Expected ':' after key");
                    break;
                }
            }
            self.advance(); // consume ':'

            let val = if let Some(v) = self.parse_value() {
                v
            } else {
                break;
            };
            pairs.push(KeyValuePair { key, value: val });

            self.skip_whitespace();
            match self.peek() {
                Some(b',') => {
                    self.advance();
                    self.skip_whitespace();
                    if self.peek() == Some(b'}') {
                        if !crate::settings::get_settings().parser.allow_trailing_commas {
                            t_err!(self, self.cursor, "Trailing commas are not allowed in JSON");
                        }
                        self.advance();
                        break;
                    }
                }
                Some(b'}') => {
                    self.advance();
                    break;
                }
                Some(b) => {
                    t_err!(
                        self,
                        self.cursor,
                        format!(
                            "Expected ',' or '}}' after object member, found '{}'",
                            b as char
                        )
                    );
                    break;
                }
                None => {
                    t_err!(self, self.cursor, "Unterminated object");
                    break;
                }
            }
        }

        Some(JsonNode::Object(
            pairs,
            Span {
                start,
                end: self.cursor,
            },
        ))
    }
}

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

    /// **Test Case**: Tolerant Parsing of Dangling Values
    ///
    /// ### Description
    /// Verifies that parsing an incomplete object key returns a partial AST and a diagnostic error.
    ///
    /// ### Test Procedure
    /// 1. Parse an object ending abruptly at the colon (`{"a":`).
    ///
    /// ### Expected Result
    /// Returns `Some(JsonNode)` and a non-empty `diagnostics` vector.
    #[test]
    fn test_tolerant_dangling_value() {
        let (node, diagnostics) = parse(r#"{"a":"#);
        assert!(node.is_some());
        assert!(!diagnostics.is_empty());
    }

    /// **Test Case**: Tolerant Parsing of Trailing Object Commas
    ///
    /// ### Description
    /// Verifies that parsing an object with a trailing comma recovers cleanly.
    ///
    /// ### Test Procedure
    /// 1. Parse `{"a": 1,}`.
    ///
    /// ### Expected Result
    /// Returns `Some(JsonNode)` representing the parsed pairs and logs a diagnostic error.
    #[test]
    fn test_tolerant_trailing_comma() {
        let (node, diagnostics) = parse(r#"{"a": 1,"#);
        assert!(node.is_some());
        assert!(!diagnostics.is_empty());
    }

    /// **Test Case**: Tolerant Parsing of Unclosed Strings
    ///
    /// ### Description
    /// Verifies that an unclosed string is captured up to the EOF.
    ///
    /// ### Test Procedure
    /// 1. Parse `{"a": "unclosed`.
    ///
    /// ### Expected Result
    /// Returns `Some(JsonNode)` capturing the string and logs an unclosed string error.
    #[test]
    fn test_tolerant_unclosed_string() {
        let (node, diagnostics) = parse(r#"{"a": "unclosed"#);
        assert!(node.is_some());
        assert!(!diagnostics.is_empty());
    }

    /// **Test Case**: Tolerant Parsing of Trailing Array Commas
    ///
    /// ### Description
    /// Verifies that parsing an array with a trailing comma recovers cleanly.
    ///
    /// ### Test Procedure
    /// 1. Parse `[1, 2,]`.
    ///
    /// ### Expected Result
    /// Returns `Some(JsonNode)` containing the parsed elements and a diagnostic error.
    #[test]
    fn test_tolerant_array_trailing_comma() {
        let (node, diagnostics) = parse(r#"[1, 2,"#);
        assert!(node.is_some());
        assert!(!diagnostics.is_empty());
    }

    /// **Test Case**: Tolerant Parsing of Just an Opening Brace
    ///
    /// ### Description
    /// Verifies that an empty, unclosed object brace recovers a minimal AST.
    ///
    /// ### Test Procedure
    /// 1. Parse `{`.
    ///
    /// ### Expected Result
    /// Returns `Some(JsonNode::Object)` and a diagnostic error.
    #[test]
    fn test_tolerant_just_opening_brace() {
        let (node, diagnostics) = parse(r#"{"#);
        assert!(node.is_some());
        assert!(!diagnostics.is_empty());
    }
}