vexy-json-core 1.5.12

Core parser for Vexy JSON's forgiving JSON syntax
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
// this_file: src/parser/mod.rs

/// Array parsing functionality.
pub mod array;
/// Boolean value parsing.
pub mod boolean;
/// Stack-based iterative parser implementation.
pub mod iterative;
/// Null value parsing.
pub mod null;
/// Number parsing with integer and float support.
pub mod number;
/// Object parsing with key-value pairs.
pub mod object;
pub mod optimized;
pub mod optimized_v2;
pub mod optimized_v3;
/// Clean recursive descent parser implementation.
pub mod recursive;
/// Parser state management.
pub mod state;
/// String parsing with escape sequence handling.
pub mod string;

use self::boolean::{parse_false, parse_true};
use self::null::parse_null;
use self::number::parse_number_token;
use self::string::parse_string_token;
use crate::ast::{Number, Token, Value};
use crate::error::repair::{EnhancedParseResult, ParsingTier, RepairAction};
use crate::error::{Error, ErrorContext, ErrorRecoveryEngineV2, Result, Span};
use crate::lexer::{FastLexer, JsonLexer, Lexer, LexerConfig, LexerMode};
use crate::optimization::ValueBuilder;
use crate::repair::JsonRepairer;
pub use iterative::{parse_iterative, IterativeParser};
pub use optimized::{
    parse_optimized, parse_optimized_with_options, parse_with_stats, OptimizedParser,
};
pub use optimized_v2::{
    parse_optimized_v2, parse_optimized_v2_with_options, parse_v2_with_stats, OptimizedParserV2,
};
pub use optimized_v3::{
    parse_optimized_v3, parse_optimized_v3_with_options, parse_v3_with_stats, OptimizedParserV3,
};
pub use recursive::{parse_recursive, RecursiveDescentParser};
use rustc_hash::FxHashMap;
pub use state::ParserState;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Configuration options for the vexy_json parser.
///
/// These options control which forgiving features are enabled during parsing.
/// By default, all forgiving features are enabled.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct ParserOptions {
    /// Whether to allow single-line and multi-line comments.
    pub allow_comments: bool,
    /// Whether to allow trailing commas in arrays and objects.
    pub allow_trailing_commas: bool,
    /// Whether to allow unquoted object keys (e.g., {key: "value"}).
    pub allow_unquoted_keys: bool,
    /// Whether to allow single-quoted strings (e.g., 'value').
    pub allow_single_quotes: bool,
    /// Whether to allow implicit top-level objects and arrays.
    /// When enabled, `key: value` becomes `{key: value}` and `1, 2, 3` becomes `[1, 2, 3]`.
    pub implicit_top_level: bool,
    /// Whether to treat newlines as commas in arrays and objects.
    pub newline_as_comma: bool,
    /// Maximum nesting depth for objects and arrays to prevent stack overflow.
    pub max_depth: usize,
    /// Enable JSON repair functionality for bracket mismatches.
    pub enable_repair: bool,
    /// Maximum number of repairs to attempt.
    pub max_repairs: usize,
    /// Prefer speed over repair quality.
    pub fast_repair: bool,
    /// Report all repairs made.
    pub report_repairs: bool,
}

impl Default for ParserOptions {
    fn default() -> Self {
        ParserOptions {
            allow_comments: true,
            allow_trailing_commas: true,
            allow_unquoted_keys: true,
            allow_single_quotes: true,
            implicit_top_level: true,
            newline_as_comma: true,
            max_depth: 128,
            enable_repair: true,
            max_repairs: 100,
            fast_repair: false,
            report_repairs: true,
        }
    }
}

/// The vexy_json parser.
///
/// Parses tokens from a Lexer into a Value tree structure.
/// Supports both strict JSON and various forgiving extensions.
pub struct Parser<'a> {
    pub(super) lexer: Box<dyn JsonLexer + 'a>,
    pub(super) original_input: &'a str,
    pub(super) options: ParserOptions,
    pub(super) current_token: Option<(Token, Span)>,
    /// Offset of the current lexer within the original input.
    /// This is 0 when the lexer is working on the full original input,
    /// but becomes non-zero when we create a new lexer from a slice.
    pub(super) state: ParserState,
    /// Value builder for optimized object and array construction
    #[allow(dead_code)]
    pub(super) value_builder: ValueBuilder,
}

impl<'a> Parser<'a> {
    /// Creates a new parser with the given input and options.
    pub fn new(input: &'a str, options: ParserOptions) -> Self {
        // Determine if we need forgiving features
        let needs_forgiving = options.allow_comments
            || options.allow_trailing_commas
            || options.allow_unquoted_keys
            || options.allow_single_quotes
            || options.implicit_top_level
            || options.newline_as_comma;

        // Create appropriate lexer based on options
        let lexer: Box<dyn JsonLexer + 'a> = if needs_forgiving {
            // Use FastLexer with forgiving mode for non-strict parsing
            let config = LexerConfig {
                mode: if options.allow_comments {
                    LexerMode::Forgiving
                } else {
                    LexerMode::Strict
                },
                collect_stats: false,
                buffer_size: 8192,
                max_depth: options.max_depth,
                track_positions: true,
            };
            Box::new(FastLexer::new(input, config))
        } else {
            // Use LogosLexer for strict parsing
            Box::new(Lexer::new(input))
        };

        Parser {
            lexer,
            original_input: input,
            options,
            current_token: None, // Will be populated by first advance()
            state: ParserState::new(),
            value_builder: ValueBuilder::new(),
        }
    }

    /// Parses the input and returns a Value.
    ///
    /// This is the main entry point for parsing. It handles:
    /// - Empty input (returns null)
    /// - Single values
    /// - Implicit arrays (when multiple comma-separated values are found)
    /// - Implicit objects (when key:value pairs are found at top level)
    pub fn parse(&mut self) -> Result<Value> {
        self.advance()?;
        self.skip_comments()?;

        // Handle empty input - check if we have only whitespace/newlines
        if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
            return Ok(Value::Null);
        }

        // Check if input is only newlines and whitespace (effectively empty)
        // NOTE: This check is only meaningful if we're at the start of the input
        // and haven't consumed any actual values yet
        // TEMPORARILY DISABLED - this seems to be causing issues
        // if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Newline) && self.is_only_whitespace_and_newlines() {
        //     return Ok(Value::Null);
        // }

        // Skip leading newlines when they appear after comments - they should not start implicit arrays
        // This is different from commas which can legitimately start implicit arrays
        if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Newline)
            && self.options.newline_as_comma
        {
            self.skip_comments_and_newlines()?;
            if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                return Ok(Value::Null);
            }
        }

        // Check if it starts with a separator (implicit array with null first element)
        if self.is_separator() && self.options.implicit_top_level {
            let mut array = vec![Value::Null];
            self.advance()?;

            loop {
                self.skip_comments_and_newlines()?;
                if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                    break;
                }

                // Check for consecutive separators (which mean null values)
                if self.is_separator() {
                    array.push(Value::Null);
                    self.advance()?;
                    continue;
                }

                array.push(self.parse_value()?);

                self.skip_comments_and_newlines()?;
                if self.is_separator() {
                    self.advance()?;
                } else if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                    break;
                } else {
                    return Err(Error::Expected {
                        expected: ", or newline or end of input".to_string(),
                        found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                        position: self.lexer.position(),
                    });
                }
            }

            return Ok(Value::Array(array));
        }

        // Try to parse as a regular value first (with implicit object support if enabled)
        // However, if we start with explicit braces/brackets, parse as regular value
        let is_explicit_structure = matches!(
            self.current_token.as_ref().map(|(t, _)| t),
            Some(&Token::LeftBrace) | Some(&Token::LeftBracket)
        );

        let first_value = if self.options.implicit_top_level && !is_explicit_structure {
            self.parse_value_or_implicit()?
        } else {
            self.parse_value()?
        };

        // Check for trailing content
        self.skip_comments()?;

        match self.current_token.as_ref().map(|(t, _)| t) {
            Some(&Token::Eof) => Ok(first_value),
            _ if is_explicit_structure => {
                // For explicit JSON structures (arrays/objects), check if there's a trailing comma
                // that should start an implicit array
                if self.options.implicit_top_level
                    && matches!(
                        self.current_token.as_ref().map(|(t, _)| t),
                        Some(&Token::Comma)
                    )
                {
                    // Treat the explicit structure as the first element of an implicit array
                    let mut array = vec![first_value];
                    self.advance()?;

                    loop {
                        self.skip_comments_and_newlines()?;
                        if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                            break;
                        }

                        // Check for consecutive separators (which mean null values)
                        if self.is_separator() {
                            array.push(Value::Null);
                            self.advance()?;
                            continue;
                        }

                        array.push(self.parse_value()?);

                        self.skip_comments_and_newlines()?;
                        if self.is_separator() {
                            self.advance()?;
                        } else if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                            break;
                        } else {
                            return Err(Error::Expected {
                                expected: ", or newline or end of input".to_string(),
                                found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                                position: self.lexer.position(),
                            });
                        }
                    }

                    Ok(Value::Array(array))
                } else {
                    // For explicit JSON structures (arrays/objects), require end of input
                    Err(Error::Expected {
                        expected: "end of input".to_string(),
                        found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                        position: self.lexer.position(),
                    })
                }
            }
            Some(&Token::Comma) | Some(&Token::Newline)
                if matches!(
                    self.current_token.as_ref().map(|(t, _)| t),
                    Some(&Token::Comma)
                ) || (self.options.newline_as_comma
                    && matches!(
                        self.current_token.as_ref().map(|(t, _)| t),
                        Some(&Token::Newline)
                    )) =>
            {
                // Check if this is just trailing newlines/whitespace by advancing and checking
                if self.options.newline_as_comma
                    && matches!(
                        self.current_token.as_ref().map(|(t, _)| t),
                        Some(&Token::Newline)
                    )
                {
                    self.advance()?;
                    self.skip_comments_and_newlines()?;

                    // If we reach EOF after skipping newlines/comments, the newline was trailing
                    if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                        return Ok(first_value);
                    } else {
                        // There's content after the newline, so this is a real separator
                        // We need to create an implicit array
                        let mut array = vec![first_value];
                        array.push(self.parse_value()?);

                        loop {
                            self.skip_comments_and_newlines()?;
                            if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                                break;
                            }

                            if self.is_separator() {
                                self.advance()?;
                                self.skip_comments_and_newlines()?;
                                if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof)
                                {
                                    break;
                                }
                            }

                            array.push(self.parse_value()?);
                        }

                        return Ok(Value::Array(array));
                    }
                }

                // It's an implicit array (for commas)
                if self.options.implicit_top_level {
                    let mut array = vec![first_value];
                    self.advance()?;

                    loop {
                        self.skip_comments_and_newlines()?;
                        if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                            break;
                        }

                        // Check for consecutive separators (which mean null values)
                        if self.is_separator() {
                            array.push(Value::Null);
                            self.advance()?;
                            continue;
                        }

                        array.push(self.parse_value()?);

                        self.skip_comments_and_newlines()?;
                        if self.is_separator() {
                            self.advance()?;
                        } else if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                            break;
                        } else {
                            return Err(Error::Expected {
                                expected: ", or newline or end of input".to_string(),
                                found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                                position: self.lexer.position(),
                            });
                        }
                    }

                    Ok(Value::Array(array))
                } else {
                    Err(Error::Expected {
                        expected: "end of input".to_string(),
                        found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                        position: self.lexer.position(),
                    })
                }
            }
            _ => {
                // Check if this is another value in an implicit array (space-separated)
                if self.options.implicit_top_level && self.is_value_token() {
                    // Create an implicit array with the first value and continue parsing
                    let mut array = vec![first_value];

                    // Parse the remaining values
                    loop {
                        // Check for consecutive separators (which mean null values)
                        if self.is_separator() {
                            array.push(Value::Null);
                            self.advance()?;
                            self.skip_comments_and_newlines()?;
                            if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                                break;
                            }
                            continue;
                        }

                        array.push(self.parse_value()?);
                        self.skip_comments()?;

                        if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                            break;
                        }

                        // Check if there's a separator
                        if self.is_separator() {
                            self.advance()?;
                            self.skip_comments_and_newlines()?;
                            if self.current_token.as_ref().map(|(t, _)| t) == Some(&Token::Eof) {
                                break;
                            }
                        } else if !self.is_value_token() {
                            return Err(Error::Expected {
                                expected: "value, separator, or end of input".to_string(),
                                found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                                position: self.lexer.position(),
                            });
                        }
                    }

                    Ok(Value::Array(array))
                } else {
                    Err(Error::Expected {
                        expected: "end of input".to_string(),
                        found: format!("{:?}", self.current_token.as_ref().map(|(t, _)| t)),
                        position: self.lexer.position(),
                    })
                }
            }
        }
    }

    pub(super) fn advance(&mut self) -> Result<()> {
        loop {
            let (token, span) = self.lexer.next_token()?;
            self.state.span = span; // Update parser state with the current token's span
            self.current_token = Some((token, span));

            match self.current_token.as_ref().map(|(t, _)| t) {
                Some(&Token::SingleLineComment) | Some(&Token::MultiLineComment) => {
                    if self.options.allow_comments {
                        continue;
                    } else {
                        return Err(Error::Custom("Comments are not allowed".to_string()));
                    }
                }
                _ => break,
            }
        }
        Ok(())
    }

    pub(super) fn skip_comments(&mut self) -> Result<()> {
        while matches!(
            self.current_token.as_ref().map(|(t, _)| t),
            Some(&Token::SingleLineComment) | Some(&Token::MultiLineComment)
        ) {
            self.advance()?;
        }
        Ok(())
    }

    /// Check if the current token can start a value
    fn is_value_token(&self) -> bool {
        matches!(
            self.current_token.as_ref().map(|(t, _)| t),
            Some(&Token::String)
                | Some(&Token::UnquotedString)
                | Some(&Token::Number)
                | Some(&Token::LeftBrace)
                | Some(&Token::LeftBracket)
                | Some(&Token::True)
                | Some(&Token::False)
                | Some(&Token::Null)
        )
    }

    /// Skips comments and optionally newlines if newline_as_comma is enabled.
    pub(super) fn skip_comments_and_newlines(&mut self) -> Result<()> {
        let mut just_had_single_line_comment = false;

        loop {
            match self.current_token.as_ref().map(|(t, _)| t) {
                Some(&Token::SingleLineComment) => {
                    just_had_single_line_comment = true;
                    self.advance()?;
                }
                Some(&Token::MultiLineComment) => {
                    just_had_single_line_comment = false;
                    self.advance()?;
                }
                Some(&Token::Newline)
                    if self.options.newline_as_comma || just_had_single_line_comment =>
                {
                    just_had_single_line_comment = false;
                    self.advance()?;
                }
                _ => break,
            }
        }
        Ok(())
    }

    /// Checks if the current token is a separator (comma or newline when newline_as_comma is enabled).
    pub(super) fn is_separator(&self) -> bool {
        matches!(
            self.current_token.as_ref().map(|(t, _)| t),
            Some(&Token::Comma)
        ) || (self.options.newline_as_comma
            && matches!(
                self.current_token.as_ref().map(|(t, _)| t),
                Some(&Token::Newline)
            ))
    }

    /// Checks if the input contains only whitespace, newlines, and comments (effectively empty).
    #[allow(dead_code)]
    fn is_only_whitespace_and_newlines(&mut self) -> bool {
        // Create a temporary lexer to peek without modifying the main lexer's state
        let current_pos = self.lexer.position();
        let remaining_input = &self.original_input[current_pos..];

        // Create same type of lexer as the main parser
        let needs_forgiving = self.options.allow_comments
            || self.options.allow_trailing_commas
            || self.options.allow_unquoted_keys
            || self.options.allow_single_quotes
            || self.options.implicit_top_level
            || self.options.newline_as_comma;

        let mut temp_lexer: Box<dyn JsonLexer> = if needs_forgiving {
            let config = LexerConfig {
                mode: if self.options.allow_comments {
                    LexerMode::Forgiving
                } else {
                    LexerMode::Strict
                },
                collect_stats: false,
                buffer_size: 8192,
                max_depth: self.options.max_depth,
                track_positions: true,
            };
            Box::new(FastLexer::new(remaining_input, config))
        } else {
            Box::new(Lexer::new(remaining_input))
        };

        loop {
            match temp_lexer.next_token() {
                Ok((Token::Eof, _)) => return true,
                Ok((Token::Newline, _)) => continue,
                Ok((Token::SingleLineComment, _)) => continue,
                Ok((Token::MultiLineComment, _)) => continue,
                Ok((_, _)) => return false,
                Err(_) => return false, // Any lexer error means it's not just whitespace
            }
        }
    }

    fn parse_value_or_implicit(&mut self) -> Result<Value> {
        self.skip_comments()?;

        // Check if it's an implicit object (key:value pattern)
        if self.options.implicit_top_level {
            match self.current_token {
                Some((Token::UnquotedString, _))
                | Some((Token::String, _))
                | Some((Token::Number, _)) => {
                    // We don't need to calculate token positions manually anymore - the lexer provides spans

                    // Read the potential key
                    let potential_key = match self.current_token {
                        Some((Token::String, span)) => {
                            // Use the helper function to parse the string
                            match parse_string_token(self.original_input, span, &self.options)? {
                                Value::String(s) => s,
                                _ => {
                                    unreachable!("parse_string_token should always return a String")
                                }
                            }
                        }
                        Some((Token::UnquotedString, span)) => {
                            // Use the span information directly - no quotes to remove
                            self.original_input[span.start..span.end].to_string()
                        }
                        Some((Token::Number, span)) => {
                            // Use the span information directly
                            self.original_input[span.start..span.end].to_string()
                        }
                        _ => unreachable!(),
                    };

                    // Save the current token info before advancing
                    let key_token = self.current_token;

                    // Advance past the key token
                    self.advance()?;
                    self.skip_comments_and_newlines()?;

                    if let Some((Token::Colon, _)) = self.current_token {
                        // It's an implicit object
                        let mut object = FxHashMap::default();

                        // Parse first key-value pair
                        self.advance()?; // Skip colon
                        let value = self.parse_value()?;
                        object.insert(potential_key, value);

                        // Continue parsing object pairs
                        loop {
                            self.skip_comments_and_newlines()?;

                            if let Some((Token::Eof, _)) = self.current_token {
                                break;
                            }

                            if self.is_separator() {
                                self.advance()?;
                                self.skip_comments_and_newlines()?;

                                if let Some((Token::Eof, _)) = self.current_token {
                                    break;
                                }
                            }

                            // Parse next key
                            let key = match self.current_token {
                                Some((Token::String, span)) => {
                                    // Use the helper function to parse the string
                                    let k = match parse_string_token(
                                        self.original_input,
                                        span,
                                        &self.options,
                                    )? {
                                        Value::String(s) => s,
                                        _ => unreachable!(
                                            "parse_string_token should always return a String"
                                        ),
                                    };
                                    self.advance()?;
                                    k
                                }
                                Some((Token::UnquotedString, span)) => {
                                    // Use the span information directly - no quotes to remove
                                    let k = self.original_input[span.start..span.end].to_string();
                                    self.advance()?;
                                    k
                                }
                                Some((Token::Number, span)) => {
                                    // Use the span information directly
                                    let k = self.original_input[span.start..span.end].to_string();
                                    self.advance()?;
                                    k
                                }
                                _ => break,
                            };

                            // Expect colon
                            self.skip_comments_and_newlines()?;
                            if !matches!(self.current_token, Some((Token::Colon, _))) {
                                return Err(Error::Expected {
                                    expected: ":".to_string(),
                                    found: format!("{:?}", self.current_token),
                                    position: self.lexer.position(),
                                });
                            }
                            self.advance()?;

                            // Parse value
                            let value = self.parse_value()?;
                            object.insert(key, value);
                        }

                        return Ok(Value::Object(object));
                    } else {
                        // Not an implicit object, parse the original token as a value
                        let value = match key_token {
                            Some((Token::String, span)) => {
                                // Use the helper function to parse the string
                                parse_string_token(self.original_input, span, &self.options)?
                            }
                            Some((Token::UnquotedString, span)) => {
                                // Handle unquoted strings as values
                                let s = self.original_input[span.start..span.end].to_string();
                                Value::String(s)
                            }
                            Some((Token::Number, span)) => {
                                // Use the same number parsing logic as parse_number_token
                                parse_number_token(self.original_input, span)?
                            }
                            _ => unreachable!(),
                        };

                        // Don't advance again - we've already advanced past the token
                        return Ok(value);
                    }
                }
                _ => {}
            }
        }

        // Parse as regular value
        self.parse_value()
    }

    pub(super) fn parse_value(&mut self) -> Result<Value> {
        self.skip_comments_and_newlines()?;

        match self.current_token {
            Some((Token::Null, _)) => {
                self.advance()?;
                parse_null()
            }
            Some((Token::True, _)) => {
                self.advance()?;
                parse_true()
            }
            Some((Token::False, _)) => {
                self.advance()?;
                parse_false()
            }
            Some((Token::String, span)) => {
                let value = parse_string_token(self.original_input, span, &self.options)?;
                self.advance()?;
                Ok(value)
            }
            Some((Token::UnquotedString, span)) => {
                // Handle unquoted strings as values - extract from span
                let s = self.original_input[span.start..span.end].to_string();
                self.advance()?;
                Ok(Value::String(s))
            }
            Some((Token::Number, span)) => {
                let value = parse_number_token(self.original_input, span)?;
                self.advance()?;
                Ok(value)
            }
            Some((Token::LeftBrace, _)) => self.parse_object(),
            Some((Token::LeftBracket, _)) => self.parse_array(),
            None => {
                // If we reached EOF where a value is expected, treat it as null (likely comment)
                if self.options.allow_comments {
                    Ok(Value::Null)
                } else {
                    Err(Error::Expected {
                        expected: "value".to_string(),
                        found: "EOF".to_string(),
                        position: self.lexer.position(),
                    })
                }
            }
            Some((Token::Eof, _)) => {
                // If we reached EOF where a value is expected, treat it as null (likely comment)
                if self.options.allow_comments {
                    Ok(Value::Null)
                } else {
                    Err(Error::Expected {
                        expected: "value".to_string(),
                        found: "EOF".to_string(),
                        position: self.lexer.position(),
                    })
                }
            }
            _ => Err(Error::Expected {
                expected: "value".to_string(),
                found: format!("{:?}", self.current_token),
                position: self.lexer.position(),
            }),
        }
    }

    pub(super) fn check_depth(&self) -> Result<()> {
        if self.state.depth >= self.options.max_depth {
            Err(Error::DepthLimitExceeded(self.lexer.position()))
        } else {
            Ok(())
        }
    }
}

/// Parses a JSON string with default options (all forgiving features enabled).
///
/// # Examples
///
/// ```
/// use vexy_json_core::parse;
///
/// // Standard JSON
/// let result = parse(r#"{"key": "value"}"#);
/// assert!(result.is_ok());
///
/// // With forgiving features - unquoted keys
/// let result = parse(r#"{key: "value"}"#);
/// assert!(result.is_ok());
/// ```
pub fn parse(input: &str) -> Result<Value> {
    let mut parser = Parser::new(input, ParserOptions::default());
    parser.parse()
}

/// Parses a JSON string with custom options.
///
/// # Arguments
///
/// * `input` - The JSON string to parse
/// * `options` - Parser configuration options
///
/// # Examples
///
/// ```
/// use vexy_json_core::{parse_with_options, ParserOptions};
///
/// let mut options = ParserOptions::default();
/// options.allow_comments = false;
///
/// let result = parse_with_options(r#"{"key": "value"}"#, options);
/// assert!(result.is_ok());
/// ```
pub fn parse_with_options(input: &str, options: ParserOptions) -> Result<Value> {
    let mut parser = Parser::new(input, options);
    parser.parse()
}

/// Enhanced parsing with three-tier fallback strategy (serde_json → vexy_json → repair)
///
/// This function implements a progressive parsing strategy:
/// 1. First tries serde_json for maximum performance on valid JSON
/// 2. Falls back to vexy_json for forgiving parsing of non-standard JSON
/// 3. Finally attempts repair for malformed JSON (bracket imbalances, etc.)
///
/// Returns an `EnhancedParseResult` that includes information about which
/// parsing tier was used and any repairs that were applied.
pub fn parse_with_fallback(input: &str, options: ParserOptions) -> EnhancedParseResult<Value> {
    // Tier 1: Try serde_json for maximum performance on valid JSON
    if let Ok(serde_value) = serde_json::from_str::<serde_json::Value>(input) {
        // Convert serde_json::Value to vexy_json::Value
        let vexy_json_value = convert_serde_to_vexy_json(serde_value);
        return EnhancedParseResult::success(vexy_json_value, ParsingTier::Fast);
    }

    // Tier 2: Try vexy_json for forgiving parsing
    match parse_with_options(input, options.clone()) {
        Ok(value) => EnhancedParseResult::success(value, ParsingTier::Forgiving),
        Err(error) => {
            // Tier 3: Try repair if enabled
            if options.enable_repair {
                parse_with_repair(input, &options)
            } else {
                EnhancedParseResult::failure(Value::Null, vec![error], ParsingTier::Forgiving)
            }
        }
    }
}

/// Parse with repair functionality for bracket mismatches and pattern-based recovery
fn parse_with_repair(input: &str, options: &ParserOptions) -> EnhancedParseResult<Value> {
    // First, try the basic JsonRepairer for bracket mismatches
    let mut repairer = if options.fast_repair {
        JsonRepairer::new_without_cache(options.max_repairs)
    } else {
        JsonRepairer::new(options.max_repairs)
    };

    match repairer.repair(input) {
        Ok((repaired_json, repairs)) => {
            // Try to parse the repaired JSON with vexy_json
            match parse_with_options(&repaired_json, options.clone()) {
                Ok(value) => {
                    EnhancedParseResult::success_with_repairs(value, repairs, ParsingTier::Repair)
                }
                Err(error) => {
                    // Basic repair didn't work, try advanced pattern-based recovery
                    parse_with_advanced_recovery(input, options, error, repairs)
                }
            }
        }
        Err(_repair_error) => {
            // Basic repair failed, try advanced pattern-based recovery
            // First try to parse to get the specific error
            match parse_with_options(input, options.clone()) {
                Ok(value) => {
                    // Shouldn't happen, but handle gracefully
                    EnhancedParseResult::success(value, ParsingTier::Repair)
                }
                Err(parse_error) => {
                    parse_with_advanced_recovery(input, options, parse_error, vec![])
                }
            }
        }
    }
}

/// Use ErrorRecoveryEngineV2 for advanced pattern-based recovery
fn parse_with_advanced_recovery(
    input: &str,
    options: &ParserOptions,
    original_error: Error,
    previous_repairs: Vec<RepairAction>,
) -> EnhancedParseResult<Value> {
    // Create the error recovery engine
    let mut recovery_engine = ErrorRecoveryEngineV2::new();
    
    // Build error context for the recovery engine
    let error_context = ErrorContext {
        error: original_error.clone(),
        input: input.to_string(),
        position: match &original_error {
            Error::UnexpectedEof(pos) => *pos,
            Error::UnterminatedString(pos) => *pos,
            Error::Expected { position, .. } => *position,
            Error::InvalidNumber(pos) => *pos,
            Error::InvalidEscape(pos) => *pos,
            Error::UnexpectedChar(_, pos) => *pos,
            Error::DepthLimitExceeded(pos) => *pos,
            _ => 0,
        },
        tokens_before: vec![], // Could be populated if we track tokens
        partial_ast: None,
        parsing_context: "top_level".to_string(),
    };
    
    // Get recovery suggestions
    let suggestions = recovery_engine.suggest_recovery(&error_context);
    
    // Try each suggestion in order of confidence
    let mut all_repairs = previous_repairs;
    
    for suggestion in suggestions {
        // Try to parse the suggested fix first
        match parse_with_options(&suggestion.fixed_input, options.clone()) {
            Ok(value) => {
                // Create repair action based on what was actually changed
                let repair_action = RepairAction {
                    position: suggestion.fix_location.start,
                    action_type: suggestion.category.clone().into(),
                    original: input[suggestion.fix_location.start..suggestion.fix_location.end.min(input.len())].to_string(),
                    replacement: match suggestion.category {
                        crate::error::SuggestionCategory::MissingBracket => {
                            if suggestion.fixed_input.ends_with('}') {
                                "}".to_string()
                            } else if suggestion.fixed_input.ends_with(']') {
                                "]".to_string()
                            } else {
                                "".to_string()
                            }
                        }
                        crate::error::SuggestionCategory::UnmatchedQuote => "\"".to_string(),
                        crate::error::SuggestionCategory::MissingComma => ",".to_string(),
                        _ => "".to_string(),
                    },
                    description: suggestion.description.clone(),
                };
                
                all_repairs.push(repair_action);
                return EnhancedParseResult::success_with_repairs(
                    value,
                    all_repairs,
                    ParsingTier::Repair,
                );
            }
            Err(_) => {
                // This suggestion didn't work, try the next one
                continue;
            }
        }
    }
    
    // All recovery attempts failed
    EnhancedParseResult::failure_with_repairs(
        Value::Null,
        vec![original_error],
        all_repairs,
        ParsingTier::Repair,
    )
}

/// Convert serde_json::Value to vexy_json::Value
fn convert_serde_to_vexy_json(serde_value: serde_json::Value) -> Value {
    match serde_value {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Number(Number::Integer(i))
            } else if let Some(f) = n.as_f64() {
                Value::Number(Number::Float(f))
            } else {
                Value::Number(Number::Float(0.0))
            }
        }
        serde_json::Value::String(s) => Value::String(s),
        serde_json::Value::Array(arr) => {
            let converted: Vec<Value> = arr.into_iter().map(convert_serde_to_vexy_json).collect();
            Value::Array(converted)
        }
        serde_json::Value::Object(obj) => {
            let converted: FxHashMap<String, Value> = obj
                .into_iter()
                .map(|(k, v)| (k, convert_serde_to_vexy_json(v)))
                .collect();
            Value::Object(converted)
        }
    }
}

/// Enhanced parsing function that reports all repairs made
pub fn parse_with_detailed_repair_tracking(
    input: &str,
    options: ParserOptions,
) -> EnhancedParseResult<Value> {
    let mut repairer = JsonRepairer::new(options.max_repairs);

    match repairer.repair_with_detailed_tracking(input) {
        Ok((repaired_json, repairs)) => match parse_with_options(&repaired_json, options) {
            Ok(value) => {
                EnhancedParseResult::success_with_repairs(value, repairs, ParsingTier::Repair)
            }
            Err(error) => EnhancedParseResult::failure_with_repairs(
                Value::Null,
                vec![error],
                repairs,
                ParsingTier::Repair,
            ),
        },
        Err(repair_error) => EnhancedParseResult::failure(
            Value::Null,
            vec![Error::RepairFailed(repair_error)],
            ParsingTier::Repair,
        ),
    }
}