perl-error 0.12.2

Error types, classification, and recovery strategies for the Perl parser ecosystem
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
//! Comprehensive unit tests for the `perl-error` crate.
//!
//! Covers: ParseError variants, helper constructors, location/suggestion methods,
//! ErrorContext enrichment, ParseBudget presets, BudgetTracker state machine,
//! ParseOutput constructors, ErrorClassifier classify/diagnostic/suggestion/explanation,
//! and recovery module types (ParseError, SyncPoint, RecoveryResult).

use perl_error::classifier::{ErrorClassifier, ParseErrorKind};
use perl_error::recovery;
use perl_error::{
    BudgetTracker, ErrorContext, ParseBudget, ParseError, ParseOutput, get_error_contexts,
};
use perl_tdd_support::must_some;

// ---------------------------------------------------------------------------
// ParseError variant construction and Display
// ---------------------------------------------------------------------------

#[test]
fn test_unexpected_eof_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::UnexpectedEof;
    let msg = format!("{err}");
    assert!(msg.contains("Unexpected end of input"), "got: {msg}");
    Ok(())
}

#[test]
fn test_unexpected_token_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::UnexpectedToken {
        expected: "semicolon".into(),
        found: "comma".into(),
        location: 42,
    };
    let msg = format!("{err}");
    assert!(msg.contains("semicolon"), "got: {msg}");
    assert!(msg.contains("comma"), "got: {msg}");
    assert!(msg.contains("42"), "got: {msg}");
    Ok(())
}

#[test]
fn test_syntax_error_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::SyntaxError { message: "bad token".into(), location: 7 };
    let msg = format!("{err}");
    assert!(msg.contains("bad token"), "got: {msg}");
    assert!(msg.contains("7"), "got: {msg}");
    Ok(())
}

#[test]
fn test_lexer_error_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::LexerError { message: "invalid byte".into() };
    let msg = format!("{err}");
    assert!(msg.contains("invalid byte"), "got: {msg}");
    Ok(())
}

#[test]
fn test_recursion_limit_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::RecursionLimit;
    let msg = format!("{err}");
    assert!(msg.contains("recursion"), "got: {msg}");
    Ok(())
}

#[test]
fn test_invalid_number_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::InvalidNumber { literal: "0xZZ".into() };
    let msg = format!("{err}");
    assert!(msg.contains("0xZZ"), "got: {msg}");
    Ok(())
}

#[test]
fn test_invalid_string_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::InvalidString;
    let msg = format!("{err}");
    assert!(msg.contains("string"), "got: {msg}");
    Ok(())
}

#[test]
fn test_unclosed_delimiter_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::UnclosedDelimiter { delimiter: '(' };
    let msg = format!("{err}");
    assert!(msg.contains('('), "got: {msg}");
    Ok(())
}

#[test]
fn test_invalid_regex_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::InvalidRegex { message: "unmatched paren".into() };
    let msg = format!("{err}");
    assert!(msg.contains("unmatched paren"), "got: {msg}");
    Ok(())
}

#[test]
fn test_nesting_too_deep_display() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::NestingTooDeep { depth: 300, max_depth: 256 };
    let msg = format!("{err}");
    assert!(msg.contains("300"), "got: {msg}");
    assert!(msg.contains("256"), "got: {msg}");
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseError helper constructors
// ---------------------------------------------------------------------------

#[test]
fn test_syntax_constructor() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::syntax("missing semi", 10);
    match &err {
        ParseError::SyntaxError { message, location } => {
            assert_eq!(message, "missing semi");
            assert_eq!(*location, 10);
        }
        other => return Err(format!("expected SyntaxError, got {other:?}").into()),
    }
    Ok(())
}

#[test]
fn test_unexpected_constructor() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("identifier", "number", 5);
    match &err {
        ParseError::UnexpectedToken { expected, found, location } => {
            assert_eq!(expected, "identifier");
            assert_eq!(found, "number");
            assert_eq!(*location, 5);
        }
        other => return Err(format!("expected UnexpectedToken, got {other:?}").into()),
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseError::location()
// ---------------------------------------------------------------------------

#[test]
fn test_location_for_unexpected_token() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("a", "b", 99);
    assert_eq!(err.location(), Some(99));
    Ok(())
}

#[test]
fn test_location_for_syntax_error() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::syntax("oops", 33);
    assert_eq!(err.location(), Some(33));
    Ok(())
}

#[test]
fn test_location_returns_none_for_other_variants() -> Result<(), Box<dyn std::error::Error>> {
    assert_eq!(ParseError::UnexpectedEof.location(), None);
    assert_eq!(ParseError::RecursionLimit.location(), None);
    assert_eq!(ParseError::InvalidString.location(), None);
    assert_eq!(ParseError::InvalidNumber { literal: "x".into() }.location(), None);
    assert_eq!(ParseError::LexerError { message: "x".into() }.location(), None);
    assert_eq!(ParseError::UnclosedDelimiter { delimiter: '"' }.location(), None);
    assert_eq!(ParseError::InvalidRegex { message: "x".into() }.location(), None);
    assert_eq!(ParseError::NestingTooDeep { depth: 1, max_depth: 1 }.location(), None);
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseError::suggestion()
// ---------------------------------------------------------------------------

#[test]
fn test_suggestion_semicolon() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("';'", "newline", 10);
    let s = must_some(err.suggestion());
    assert!(s.contains("semicolon"), "got: {s}");
    Ok(())
}

#[test]
fn test_suggestion_right_brace() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("'}'", "eof", 10);
    let s = must_some(err.suggestion());
    assert!(s.contains('}'), "got: {s}");
    Ok(())
}

#[test]
fn test_suggestion_right_paren() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("')'", "eof", 10);
    let s = must_some(err.suggestion());
    assert!(s.contains(')'), "got: {s}");
    Ok(())
}

#[test]
fn test_suggestion_unclosed_delimiter() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::UnclosedDelimiter { delimiter: '"' };
    let s = must_some(err.suggestion());
    assert!(s.contains('"'), "got: {s}");
    Ok(())
}

#[test]
fn test_suggestion_none_for_generic_token() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("identifier", "number", 0);
    assert!(err.suggestion().is_none());
    Ok(())
}

#[test]
fn test_suggestion_none_for_non_token_errors() -> Result<(), Box<dyn std::error::Error>> {
    assert!(ParseError::UnexpectedEof.suggestion().is_none());
    assert!(ParseError::RecursionLimit.suggestion().is_none());
    assert!(ParseError::InvalidString.suggestion().is_none());
    assert!(ParseError::InvalidNumber { literal: "x".into() }.suggestion().is_none());
    assert!(ParseError::InvalidRegex { message: "x".into() }.suggestion().is_none());
    assert!(ParseError::NestingTooDeep { depth: 1, max_depth: 1 }.suggestion().is_none());
    assert!(ParseError::LexerError { message: "x".into() }.suggestion().is_none());
    assert!(ParseError::syntax("x", 0).suggestion().is_none());
    Ok(())
}

// ---------------------------------------------------------------------------
// From<RegexError> for ParseError
// ---------------------------------------------------------------------------

#[test]
fn test_from_regex_error() -> Result<(), Box<dyn std::error::Error>> {
    let regex_err = perl_regex::RegexError::Syntax { message: "bad group".into(), offset: 5 };
    let parse_err: ParseError = regex_err.into();
    match &parse_err {
        ParseError::SyntaxError { message, location } => {
            assert_eq!(message, "bad group");
            assert_eq!(*location, 5);
        }
        other => return Err(format!("expected SyntaxError, got {other:?}").into()),
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseError Clone + PartialEq
// ---------------------------------------------------------------------------

#[test]
fn test_parse_error_clone_and_eq() -> Result<(), Box<dyn std::error::Error>> {
    let err = ParseError::unexpected("a", "b", 1);
    let cloned = err.clone();
    assert_eq!(err, cloned);
    Ok(())
}

// ---------------------------------------------------------------------------
// get_error_contexts
// ---------------------------------------------------------------------------

#[test]
fn test_error_contexts_multiline() -> Result<(), Box<dyn std::error::Error>> {
    let source = "first\nsecond\nthird";
    // byte offset 6 = start of "second"
    let errors = vec![ParseError::syntax("oops", 6)];
    let ctxs = get_error_contexts(&errors, source);
    assert_eq!(ctxs.len(), 1);
    assert_eq!(ctxs[0].line, 1);
    assert_eq!(ctxs[0].source_line, "second");
    Ok(())
}

#[test]
fn test_error_contexts_no_location_falls_back_to_eof() -> Result<(), Box<dyn std::error::Error>> {
    let source = "hello";
    let errors = vec![ParseError::UnexpectedEof];
    let ctxs = get_error_contexts(&errors, source);
    assert_eq!(ctxs.len(), 1);
    // Should not panic even though location() returns None
    Ok(())
}

#[test]
fn test_error_contexts_empty_source() -> Result<(), Box<dyn std::error::Error>> {
    let source = "";
    let errors = vec![ParseError::syntax("empty", 0)];
    let ctxs = get_error_contexts(&errors, source);
    assert_eq!(ctxs.len(), 1);
    Ok(())
}

#[test]
fn test_error_contexts_preserves_suggestion() -> Result<(), Box<dyn std::error::Error>> {
    let source = "my $x = 1";
    let errors = vec![ParseError::unexpected("';'", "eof", 0)];
    let ctxs = get_error_contexts(&errors, source);
    assert_eq!(ctxs.len(), 1);
    assert!(ctxs[0].suggestion.is_some());
    Ok(())
}

#[test]
fn test_error_context_struct_fields() -> Result<(), Box<dyn std::error::Error>> {
    let ctx = ErrorContext {
        error: ParseError::UnexpectedEof,
        line: 3,
        column: 7,
        source_line: "some code".into(),
        suggestion: Some("fix it".into()),
    };
    assert_eq!(ctx.line, 3);
    assert_eq!(ctx.column, 7);
    assert_eq!(ctx.source_line, "some code");
    assert_eq!(ctx.suggestion.as_deref(), Some("fix it"));
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseBudget presets
// ---------------------------------------------------------------------------

#[test]
fn test_parse_budget_for_ide() -> Result<(), Box<dyn std::error::Error>> {
    let ide = ParseBudget::for_ide();
    let def = ParseBudget::default();
    assert_eq!(ide, def);
    Ok(())
}

#[test]
fn test_parse_budget_strict_is_tighter() -> Result<(), Box<dyn std::error::Error>> {
    let strict = ParseBudget::strict();
    let def = ParseBudget::default();
    assert!(strict.max_errors < def.max_errors);
    assert!(strict.max_depth < def.max_depth);
    assert!(strict.max_tokens_skipped < def.max_tokens_skipped);
    assert!(strict.max_recoveries < def.max_recoveries);
    Ok(())
}

#[test]
fn test_parse_budget_unlimited() -> Result<(), Box<dyn std::error::Error>> {
    let u = ParseBudget::unlimited();
    assert_eq!(u.max_errors, usize::MAX);
    assert_eq!(u.max_depth, usize::MAX);
    assert_eq!(u.max_tokens_skipped, usize::MAX);
    assert_eq!(u.max_recoveries, usize::MAX);
    Ok(())
}

#[test]
fn test_parse_budget_clone_and_copy() -> Result<(), Box<dyn std::error::Error>> {
    let b = ParseBudget::default();
    let c = b; // Copy
    assert_eq!(b, c);
    Ok(())
}

// ---------------------------------------------------------------------------
// BudgetTracker
// ---------------------------------------------------------------------------

#[test]
fn test_budget_tracker_new_is_zeroed() -> Result<(), Box<dyn std::error::Error>> {
    let t = BudgetTracker::new();
    assert_eq!(t.errors_emitted, 0);
    assert_eq!(t.current_depth, 0);
    assert_eq!(t.max_depth_reached, 0);
    assert_eq!(t.tokens_skipped, 0);
    assert_eq!(t.recoveries_attempted, 0);
    Ok(())
}

#[test]
fn test_budget_tracker_default_equals_new() -> Result<(), Box<dyn std::error::Error>> {
    let a = BudgetTracker::new();
    let b = BudgetTracker::default();
    assert_eq!(a.errors_emitted, b.errors_emitted);
    Ok(())
}

#[test]
fn test_enter_exit_depth_tracking() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    t.enter_depth();
    t.enter_depth();
    t.enter_depth();
    assert_eq!(t.current_depth, 3);
    assert_eq!(t.max_depth_reached, 3);

    t.exit_depth();
    assert_eq!(t.current_depth, 2);
    // max_depth_reached should not decrease
    assert_eq!(t.max_depth_reached, 3);

    t.exit_depth();
    t.exit_depth();
    assert_eq!(t.current_depth, 0);
    Ok(())
}

#[test]
fn test_exit_depth_saturates_at_zero() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    t.exit_depth(); // should not underflow
    assert_eq!(t.current_depth, 0);
    Ok(())
}

#[test]
fn test_record_error_increments() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    t.record_error();
    t.record_error();
    assert_eq!(t.errors_emitted, 2);
    Ok(())
}

#[test]
fn test_record_skip_accumulates() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    t.record_skip(5);
    t.record_skip(3);
    assert_eq!(t.tokens_skipped, 8);
    Ok(())
}

#[test]
fn test_record_recovery_increments() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    t.record_recovery();
    assert_eq!(t.recoveries_attempted, 1);
    Ok(())
}

#[test]
fn test_begin_recovery_returns_true_and_increments() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget { max_recoveries: 2, ..Default::default() };
    let mut t = BudgetTracker::new();
    assert!(t.begin_recovery(&budget));
    assert_eq!(t.recoveries_attempted, 1);
    assert!(t.begin_recovery(&budget));
    assert_eq!(t.recoveries_attempted, 2);
    // Now exhausted
    assert!(!t.begin_recovery(&budget));
    assert_eq!(t.recoveries_attempted, 2); // should not increment further
    Ok(())
}

#[test]
fn test_errors_exhausted_boundary() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget { max_errors: 1, ..Default::default() };
    let mut t = BudgetTracker::new();
    assert!(!t.errors_exhausted(&budget));
    t.record_error();
    assert!(t.errors_exhausted(&budget));
    Ok(())
}

#[test]
fn test_depth_would_exceed_boundary() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget { max_depth: 1, ..Default::default() };
    let mut t = BudgetTracker::new();
    assert!(!t.depth_would_exceed(&budget));
    t.enter_depth();
    assert!(t.depth_would_exceed(&budget));
    Ok(())
}

#[test]
fn test_skip_would_exceed_boundary() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget { max_tokens_skipped: 5, ..Default::default() };
    let mut t = BudgetTracker::new();
    assert!(!t.skip_would_exceed(&budget, 5));
    assert!(t.skip_would_exceed(&budget, 6));
    t.record_skip(5);
    assert!(t.skip_would_exceed(&budget, 1));
    Ok(())
}

#[test]
fn test_can_skip_more_exact_boundary() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget { max_tokens_skipped: 10, ..Default::default() };
    let mut t = BudgetTracker::new();
    assert!(t.can_skip_more(&budget, 10));
    assert!(!t.can_skip_more(&budget, 11));
    t.record_skip(10);
    assert!(t.can_skip_more(&budget, 0));
    assert!(!t.can_skip_more(&budget, 1));
    Ok(())
}

#[test]
fn test_recoveries_exhausted_boundary() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget { max_recoveries: 0, ..Default::default() };
    let t = BudgetTracker::new();
    assert!(t.recoveries_exhausted(&budget));
    Ok(())
}

#[test]
fn test_budget_tracker_clone() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    t.record_error();
    t.enter_depth();
    t.record_skip(7);
    t.record_recovery();

    let c = t.clone();
    assert_eq!(c.errors_emitted, 1);
    assert_eq!(c.current_depth, 1);
    assert_eq!(c.max_depth_reached, 1);
    assert_eq!(c.tokens_skipped, 7);
    assert_eq!(c.recoveries_attempted, 1);
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseOutput
// ---------------------------------------------------------------------------

fn make_program_node() -> perl_ast::Node {
    use perl_ast::{NodeKind, SourceLocation};
    perl_ast::Node::new(
        NodeKind::Program { statements: vec![] },
        SourceLocation { start: 0, end: 0 },
    )
}

#[test]
fn test_parse_output_success_state() -> Result<(), Box<dyn std::error::Error>> {
    let out = ParseOutput::success(make_program_node());
    assert!(out.is_ok());
    assert!(!out.has_errors());
    assert_eq!(out.error_count(), 0);
    assert!(!out.terminated_early);
    assert_eq!(out.budget_usage.errors_emitted, 0);
    Ok(())
}

#[test]
fn test_parse_output_with_errors_state() -> Result<(), Box<dyn std::error::Error>> {
    let errs = vec![ParseError::UnexpectedEof, ParseError::InvalidString];
    let out = ParseOutput::with_errors(make_program_node(), errs);
    assert!(!out.is_ok());
    assert!(out.has_errors());
    assert_eq!(out.error_count(), 2);
    assert_eq!(out.budget_usage.errors_emitted, 2);
    assert!(!out.terminated_early);
    Ok(())
}

#[test]
fn test_parse_output_finish_preserves_all_fields() -> Result<(), Box<dyn std::error::Error>> {
    let mut tracker = BudgetTracker::new();
    tracker.errors_emitted = 10;
    tracker.tokens_skipped = 50;
    tracker.recoveries_attempted = 7;
    tracker.max_depth_reached = 20;
    tracker.current_depth = 3;

    let errs = vec![ParseError::RecursionLimit];
    let out = ParseOutput::finish(make_program_node(), errs, tracker, true);

    assert!(out.terminated_early);
    assert_eq!(out.error_count(), 1);
    assert_eq!(out.budget_usage.errors_emitted, 10);
    assert_eq!(out.budget_usage.tokens_skipped, 50);
    assert_eq!(out.budget_usage.recoveries_attempted, 7);
    assert_eq!(out.budget_usage.max_depth_reached, 20);
    assert_eq!(out.budget_usage.current_depth, 3);
    Ok(())
}

#[test]
fn test_parse_output_with_empty_errors() -> Result<(), Box<dyn std::error::Error>> {
    let out = ParseOutput::with_errors(make_program_node(), vec![]);
    assert!(out.is_ok());
    assert_eq!(out.error_count(), 0);
    Ok(())
}

// ---------------------------------------------------------------------------
// ErrorClassifier — construction
// ---------------------------------------------------------------------------

#[test]
fn test_error_classifier_default_and_new() -> Result<(), Box<dyn std::error::Error>> {
    let _a = ErrorClassifier::new();
    let _b = ErrorClassifier;
    Ok(())
}

// ---------------------------------------------------------------------------
// ErrorClassifier::classify
// ---------------------------------------------------------------------------

fn make_error_node(start: usize, end: usize) -> perl_ast::Node {
    use perl_ast::{NodeKind, SourceLocation};
    perl_ast::Node::new(
        NodeKind::Error { message: "test".into(), expected: vec![], found: None, partial: None },
        SourceLocation { start, end },
    )
}

#[test]
fn test_classify_unclosed_double_quote() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    // Odd number of double quotes → UnclosedString
    let source = r#"my $x = "hello"#;
    let node = make_error_node(8, 15);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnclosedString);
    Ok(())
}

#[test]
fn test_classify_unclosed_single_quote() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "my $x = 'hello";
    let node = make_error_node(8, 14);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnclosedString);
    Ok(())
}

#[test]
fn test_classify_unclosed_regex() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    // Even quotes, error_text starts with '/' and no closing '/'
    let source = "my $x = /abc";
    let node = make_error_node(8, 12);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnclosedRegex);
    Ok(())
}

#[test]
fn test_classify_missing_semicolon_my() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "my $x = 42\nmy $y = 10;";
    let node = make_error_node(3, 10);
    assert_eq!(c.classify(&node, source), ParseErrorKind::MissingSemicolon);
    Ok(())
}

#[test]
fn test_classify_missing_semicolon_print() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    // Avoid quoted strings so error_text window doesn't trigger UnclosedString
    let source = "print $x\n";
    let node = make_error_node(6, 8);
    assert_eq!(c.classify(&node, source), ParseErrorKind::MissingSemicolon);
    Ok(())
}

#[test]
fn test_classify_missing_semicolon_say() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "say $x\n";
    let node = make_error_node(4, 6);
    assert_eq!(c.classify(&node, source), ParseErrorKind::MissingSemicolon);
    Ok(())
}

#[test]
fn test_classify_missing_semicolon_return() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "return 1\n";
    let node = make_error_node(7, 8);
    assert_eq!(c.classify(&node, source), ParseErrorKind::MissingSemicolon);
    Ok(())
}

#[test]
fn test_classify_missing_semicolon_our() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "our $x = 42\n";
    let node = make_error_node(4, 11);
    assert_eq!(c.classify(&node, source), ParseErrorKind::MissingSemicolon);
    Ok(())
}

#[test]
fn test_classify_missing_semicolon_local() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "local $x = 42\n";
    let node = make_error_node(6, 13);
    assert_eq!(c.classify(&node, source), ParseErrorKind::MissingSemicolon);
    Ok(())
}

#[test]
fn test_classify_unclosed_parenthesis() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "func(1, 2;\n";
    let node = make_error_node(4, 10);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnclosedParenthesis);
    Ok(())
}

#[test]
fn test_classify_unclosed_bracket() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "my @a = [1, 2;\n";
    let node = make_error_node(8, 13);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnclosedBracket);
    Ok(())
}

#[test]
fn test_classify_unclosed_brace() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "if (1) {\n";
    let node = make_error_node(7, 8);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnclosedBrace);
    Ok(())
}

#[test]
fn test_classify_unexpected_eof() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    let source = "x;";
    // Error at last byte
    let node = make_error_node(1, 2);
    assert_eq!(c.classify(&node, source), ParseErrorKind::UnexpectedEof);
    Ok(())
}

#[test]
fn test_classify_falls_back_to_invalid_syntax() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    // Even quotes, no unclosed delimiters, no statement keywords, not at EOF
    let source = "abc def ghi;\n";
    let node = make_error_node(4, 7);
    assert_eq!(c.classify(&node, source), ParseErrorKind::InvalidSyntax);
    Ok(())
}

// ---------------------------------------------------------------------------
// ErrorClassifier::get_diagnostic_message
// ---------------------------------------------------------------------------

#[test]
fn test_diagnostic_message_all_variants() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();

    let cases: Vec<(ParseErrorKind, &str)> = vec![
        (ParseErrorKind::UnexpectedToken { expected: "foo".into(), found: "bar".into() }, "foo"),
        (ParseErrorKind::UnclosedString, "string"),
        (ParseErrorKind::UnclosedRegex, "regular expression"),
        (ParseErrorKind::UnclosedBlock, "block"),
        (ParseErrorKind::MissingSemicolon, "semicolon"),
        (ParseErrorKind::InvalidSyntax, "Invalid syntax"),
        (ParseErrorKind::UnclosedParenthesis, "parenthesis"),
        (ParseErrorKind::UnclosedBracket, "bracket"),
        (ParseErrorKind::UnclosedBrace, "brace"),
        (ParseErrorKind::UnterminatedHeredoc, "heredoc"),
        (ParseErrorKind::InvalidVariableName, "variable"),
        (ParseErrorKind::InvalidSubroutineName, "subroutine"),
        (ParseErrorKind::MissingOperator, "operator"),
        (ParseErrorKind::MissingOperand, "operand"),
        (ParseErrorKind::UnexpectedEof, "end of file"),
    ];

    for (kind, substring) in cases {
        let msg = c.get_diagnostic_message(&kind);
        assert!(
            msg.to_lowercase().contains(&substring.to_lowercase()),
            "message for {kind:?} = {msg:?} should contain {substring:?}"
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// ErrorClassifier::get_suggestion
// ---------------------------------------------------------------------------

#[test]
fn test_suggestion_all_variants_with_some() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();

    let kinds_with_suggestions = vec![
        ParseErrorKind::MissingSemicolon,
        ParseErrorKind::UnclosedString,
        ParseErrorKind::UnclosedParenthesis,
        ParseErrorKind::UnclosedBracket,
        ParseErrorKind::UnclosedBrace,
        ParseErrorKind::UnclosedBlock,
        ParseErrorKind::UnclosedRegex,
        ParseErrorKind::UnterminatedHeredoc,
        ParseErrorKind::InvalidVariableName,
        ParseErrorKind::InvalidSubroutineName,
        ParseErrorKind::MissingOperator,
        ParseErrorKind::MissingOperand,
        ParseErrorKind::UnexpectedEof,
        ParseErrorKind::UnexpectedToken { expected: "semi".into(), found: "x".into() },
    ];

    for kind in kinds_with_suggestions {
        assert!(c.get_suggestion(&kind).is_some(), "expected Some suggestion for {kind:?}");
    }
    Ok(())
}

#[test]
fn test_suggestion_none_for_invalid_syntax() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    assert!(c.get_suggestion(&ParseErrorKind::InvalidSyntax).is_none());
    Ok(())
}

// ---------------------------------------------------------------------------
// ErrorClassifier::get_explanation
// ---------------------------------------------------------------------------

#[test]
fn test_explanation_some_variants() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();

    let kinds_with_explanation = vec![
        ParseErrorKind::MissingSemicolon,
        ParseErrorKind::UnclosedString,
        ParseErrorKind::UnclosedRegex,
        ParseErrorKind::UnterminatedHeredoc,
        ParseErrorKind::InvalidVariableName,
        ParseErrorKind::UnclosedBlock,
    ];

    for kind in kinds_with_explanation {
        assert!(c.get_explanation(&kind).is_some(), "expected Some explanation for {kind:?}");
    }
    Ok(())
}

#[test]
fn test_explanation_none_for_other_variants() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();

    let kinds_without_explanation = vec![
        ParseErrorKind::InvalidSyntax,
        ParseErrorKind::UnclosedParenthesis,
        ParseErrorKind::UnclosedBracket,
        ParseErrorKind::UnclosedBrace,
        ParseErrorKind::MissingOperator,
        ParseErrorKind::MissingOperand,
        ParseErrorKind::UnexpectedEof,
        ParseErrorKind::InvalidSubroutineName,
        ParseErrorKind::UnexpectedToken { expected: "a".into(), found: "b".into() },
    ];

    for kind in kinds_without_explanation {
        assert!(c.get_explanation(&kind).is_none(), "expected None explanation for {kind:?}");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// ParseErrorKind Clone + PartialEq
// ---------------------------------------------------------------------------

#[test]
fn test_parse_error_kind_clone_and_eq() -> Result<(), Box<dyn std::error::Error>> {
    let kind = ParseErrorKind::UnclosedString;
    let cloned = kind.clone();
    assert_eq!(kind, cloned);
    Ok(())
}

#[test]
fn test_parse_error_kind_debug() -> Result<(), Box<dyn std::error::Error>> {
    let kind = ParseErrorKind::MissingSemicolon;
    let dbg = format!("{kind:?}");
    assert!(dbg.contains("MissingSemicolon"), "got: {dbg}");
    Ok(())
}

// ---------------------------------------------------------------------------
// recovery module types
// ---------------------------------------------------------------------------

#[test]
fn test_recovery_parse_error_new() -> Result<(), Box<dyn std::error::Error>> {
    use perl_position_tracking::{Position, Range};

    let range = Range::new(Position::new(0, 1, 1), Position::new(5, 1, 6));
    let err = recovery::ParseError::new("test error".into(), range);
    assert_eq!(err.message, "test error");
    assert!(err.expected.is_empty());
    assert!(err.found.is_empty());
    assert!(err.recovery_hint.is_none());
    Ok(())
}

#[test]
fn test_recovery_parse_error_builder_chain() -> Result<(), Box<dyn std::error::Error>> {
    use perl_position_tracking::{Position, Range};

    let range = Range::new(Position::new(0, 1, 1), Position::new(5, 1, 6));
    let err = recovery::ParseError::new("err".into(), range)
        .with_expected(vec!["semi".into(), "brace".into()])
        .with_found("comma".into())
        .with_hint("add semicolon".into());

    assert_eq!(err.expected.len(), 2);
    assert_eq!(err.found, "comma");
    assert_eq!(err.recovery_hint.as_deref(), Some("add semicolon"));
    Ok(())
}

#[test]
fn test_recovery_parse_error_clone() -> Result<(), Box<dyn std::error::Error>> {
    use perl_position_tracking::{Position, Range};

    let range = Range::new(Position::new(0, 1, 1), Position::new(1, 1, 2));
    let err = recovery::ParseError::new("x".into(), range).with_hint("h".into());
    let cloned = err.clone();
    assert_eq!(cloned.message, "x");
    assert_eq!(cloned.recovery_hint.as_deref(), Some("h"));
    Ok(())
}

#[test]
fn test_sync_point_equality() -> Result<(), Box<dyn std::error::Error>> {
    assert_eq!(recovery::SyncPoint::Semicolon, recovery::SyncPoint::Semicolon);
    assert_ne!(recovery::SyncPoint::Semicolon, recovery::SyncPoint::CloseBrace);
    assert_ne!(recovery::SyncPoint::Keyword, recovery::SyncPoint::Eof);
    Ok(())
}

#[test]
fn test_sync_point_copy() -> Result<(), Box<dyn std::error::Error>> {
    let sp = recovery::SyncPoint::Eof;
    let sp2 = sp; // Copy
    assert_eq!(sp, sp2);
    Ok(())
}

#[test]
fn test_recovery_result_equality() -> Result<(), Box<dyn std::error::Error>> {
    assert_eq!(recovery::RecoveryResult::Recovered(3), recovery::RecoveryResult::Recovered(3));
    assert_ne!(recovery::RecoveryResult::Recovered(1), recovery::RecoveryResult::Recovered(2));
    assert_eq!(recovery::RecoveryResult::AtSyncPoint, recovery::RecoveryResult::AtSyncPoint);
    assert_eq!(
        recovery::RecoveryResult::BudgetExhausted,
        recovery::RecoveryResult::BudgetExhausted
    );
    assert_eq!(recovery::RecoveryResult::ReachedEof, recovery::RecoveryResult::ReachedEof);
    Ok(())
}

#[test]
fn test_recovery_result_debug() -> Result<(), Box<dyn std::error::Error>> {
    let r = recovery::RecoveryResult::Recovered(5);
    let dbg = format!("{r:?}");
    assert!(dbg.contains("Recovered"), "got: {dbg}");
    assert!(dbg.contains('5'), "got: {dbg}");
    Ok(())
}

// ---------------------------------------------------------------------------
// Edge cases and integration-style checks
// ---------------------------------------------------------------------------

#[test]
fn test_classify_error_text_boundary_beyond_source() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    // Error node start at end of source — should not panic
    let source = "ab";
    let node = make_error_node(2, 2);
    // At EOF
    let _kind = c.classify(&node, source);
    Ok(())
}

#[test]
fn test_classify_single_char_source() -> Result<(), Box<dyn std::error::Error>> {
    let c = ErrorClassifier::new();
    // Use a minimal source to test boundary without triggering underflow on empty string
    let source = "x";
    let node = make_error_node(0, 1);
    let kind = c.classify(&node, source);
    assert_eq!(kind, ParseErrorKind::UnexpectedEof);
    Ok(())
}

#[test]
fn test_multiple_error_contexts() -> Result<(), Box<dyn std::error::Error>> {
    let source = "line1\nline2\nline3";
    let errors = vec![
        ParseError::syntax("e1", 0),
        ParseError::syntax("e2", 6),
        ParseError::syntax("e3", 12),
    ];
    let ctxs = get_error_contexts(&errors, source);
    assert_eq!(ctxs.len(), 3);
    assert_eq!(ctxs[0].line, 0);
    assert_eq!(ctxs[1].line, 1);
    assert_eq!(ctxs[2].line, 2);
    Ok(())
}

#[test]
fn test_budget_tracker_saturating_operations() -> Result<(), Box<dyn std::error::Error>> {
    let mut t = BudgetTracker::new();
    // Test saturating_add on skip
    t.record_skip(usize::MAX);
    t.record_skip(1); // should saturate, not overflow
    assert_eq!(t.tokens_skipped, usize::MAX);

    // Test saturating_add on error
    t.errors_emitted = usize::MAX;
    t.record_error(); // should saturate
    assert_eq!(t.errors_emitted, usize::MAX);

    // Test saturating_add on recovery
    t.recoveries_attempted = usize::MAX;
    t.record_recovery(); // should saturate
    assert_eq!(t.recoveries_attempted, usize::MAX);
    Ok(())
}

#[test]
fn test_begin_recovery_saturating() -> Result<(), Box<dyn std::error::Error>> {
    let budget = ParseBudget::unlimited();
    let mut t = BudgetTracker::new();
    t.recoveries_attempted = usize::MAX - 1;
    assert!(t.begin_recovery(&budget));
    assert_eq!(t.recoveries_attempted, usize::MAX);
    // At MAX, should still be able to succeed if budget is unlimited
    // But begin_recovery checks >=, so MAX >= MAX is true → returns false
    assert!(!t.begin_recovery(&budget));
    Ok(())
}