tabnas-json5 0.5.20

The JSON5 grammar plugin for the tabnas parsing engine, over the jsonic base grammar
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
// In-language tests: the behaviour the shared fixtures cannot pin, and
// the same cases `go/json5_test.go` and `ts/test/json5.test.ts` carry,
// so the three suites can be read side by side.

mod common;

use std::sync::Arc;
use std::thread;

use tabnas::Tabnas;
use tabnas_json5::{json5, make, make_with, parse, parse_with, plugin, Json5Options};

use common::{json, to_value};

/// A fresh parser with the given overrides on the defaults.
fn parser(configure: impl FnOnce(&mut Json5Options)) -> Tabnas {
    let mut options = Json5Options::default();
    configure(&mut options);
    make_with(options)
}

fn parsed(parser: &Tabnas, src: &str) -> String {
    json(&parse_with(parser, src).unwrap_or_else(|error| panic!("{src:?}: {error}")))
}

fn code(parser: &Tabnas, src: &str) -> String {
    match parse_with(parser, src) {
        Ok(value) => panic!("{src:?} parsed to {}", json(&value)),
        Err(error) => error.code,
    }
}

// --- go/json5_test.go -------------------------------------------------

#[test]
fn primitives() {
    let j = make();
    for (src, want) in [
        ("true", "true"),
        ("false", "false"),
        ("null", "null"),
        (r#""hello""#, r#""hello""#),
        ("'hello'", r#""hello""#),
        ("42", "42"),
        ("3.14", "3.14"),
        ("-7", "-7"),
        ("+5", "5"),
        (".5", "0.5"),
        ("5.", "5"),
        ("1e10", "10000000000"),
        ("1.5e-2", "0.015"),
        ("0x1F", "31"),
        ("0xDEADBEEF", "3735928559"),
        ("-0x10", "-16"),
    ] {
        assert_eq!(parsed(&j, src), want, "{src:?}");
    }
}

#[test]
fn infinity_and_nan() {
    let j = make();
    for src in ["Infinity", "+Infinity"] {
        assert_eq!(parsed(&j, src), "Infinity", "{src:?}");
    }
    assert_eq!(parsed(&j, "-Infinity"), "-Infinity");
    for src in ["NaN", "+NaN", "-NaN"] {
        assert_eq!(parsed(&j, src), "NaN", "{src:?}");
    }

    // Can be disabled.
    let jn = parser(|o| o.infinity = false);
    assert_eq!(code(&jn, "Infinity"), "unexpected");
    assert_eq!(code(&jn, "NaN"), "unexpected");
}

#[test]
fn objects() {
    let j = make();
    for (src, want) in [
        ("{}", "{}"),
        (r#"{"a":1}"#, r#"{"a":1}"#),
        ("{a:1}", r#"{"a":1}"#),
        ("{a:1,b:2}", r#"{"a":1,"b":2}"#),
        ("{a:1, 'b':2}", r#"{"a":1,"b":2}"#),
        ("{ nested: { x: 1 } }", r#"{"nested":{"x":1}}"#),
        ("{$id:1, _n:2, a1:3}", r#"{"$id":1,"_n":2,"a1":3}"#),
    ] {
        assert_eq!(parsed(&j, src), want, "{src:?}");
    }
}

#[test]
fn arrays() {
    let j = make();
    for (src, want) in [
        ("[]", "[]"),
        ("[1]", "[1]"),
        ("[1,2,3]", "[1,2,3]"),
        (r#"["a","b"]"#, r#"["a","b"]"#),
        ("[[1,2],[3,4]]", "[[1,2],[3,4]]"),
    ] {
        assert_eq!(parsed(&j, src), want, "{src:?}");
    }
}

#[test]
fn trailing_commas() {
    let j = make();
    for (src, want) in [
        ("[1,2,3,]", "[1,2,3]"),
        ("{a:1,b:2,}", r#"{"a":1,"b":2}"#),
        ("[1,]", "[1]"),
        ("{a:1,}", r#"{"a":1}"#),
        ("[ 1 , 2 , ]", "[1,2]"),
    ] {
        assert_eq!(parsed(&j, src), want, "{src:?}");
    }
}

#[test]
fn comments() {
    let j = make();
    for (src, want) in [
        ("// hello\n42", "42"),
        ("/* block */ 42", "42"),
        ("{ a: 1, /* mid */ b: 2 }", r#"{"a":1,"b":2}"#),
        ("[/* a */ 1, /* b */ 2]", "[1,2]"),
        ("/* multi\nline\ncomment */ [1,2]", "[1,2]"),
    ] {
        assert_eq!(parsed(&j, src), want, "{src:?}");
    }

    // Hash comments are not JSON5 by default.
    assert_eq!(code(&j, "# nope\n42"), "unexpected");

    // Can be enabled.
    let jh = parser(|o| o.hash_comment = true);
    assert_eq!(parsed(&jh, "# hello\n42"), "42");
}

#[test]
fn strings() {
    let j = make();
    for (src, want) in [
        (r#""hello""#, "hello"),
        ("'hello'", "hello"),
        (r#""he said \"hi\"""#, r#"he said "hi""#),
        (r#"'he said \'hi\''"#, "he said 'hi'"),
        (r#""a\tb""#, "a\tb"),
        (r#""a\nb""#, "a\nb"),
        (r#""aAb""#, "aAb"),
        (r#""a\x41b""#, "aAb"),
        (r#""\0""#, "\0"),
        ("\"line1\\\nline2\"", "line1line2"),
        ("\"line1\\\r\nline2\"", "line1line2"),
    ] {
        match parse_with(&j, src) {
            Ok(tabnas::Value::String(got)) => assert_eq!(got, want, "{src:?}"),
            other => panic!("{src:?}: {other:?}"),
        }
    }

    // Backticks are not JSON5 by default.
    assert_eq!(code(&j, "`backtick`"), "unexpected");

    // Can be enabled.
    let jb = parser(|o| o.backtick_string = true);
    assert_eq!(parsed(&jb, "`backtick`"), r#""backtick""#);
}

#[test]
fn rejects_non_json5() {
    let j = make();
    for src in [
        "", "foo", "0o17", "0b101", "1_000", "1,2,3", "a:1", "{,}", "{10:1}",
    ] {
        assert!(parse_with(&j, src).is_err(), "{src:?} expected an error");
    }
}

/// Mirrors the TypeScript `require-value` test: empty input under the
/// default requireValue option fails with `json5_empty` (message matching
/// /JSON5/), while requireValue=false lets it parse to `null`.
#[test]
fn require_value() {
    let j = make();
    let error = parse_with(&j, "").expect_err("empty input is an error");
    assert_eq!(error.code, "json5_empty");
    assert!(error.to_string().contains("JSON5"), "{error}");
    assert_eq!(error.detail, "JSON5 input must contain a value");
    assert!(error.hint.contains("top-level value"), "{}", error.hint);

    let error = parse_with(&j, "   // nothing").expect_err("no value is an error");
    assert_eq!(error.code, "json5_no_value");

    // A direct `parse` on the instance also fails (lex.empty is off),
    // though with the engine's generic error; the package-level
    // `parse_with` is the counterpart of the TypeScript wrapped start
    // and the Go `Parse(j, src)`.
    assert!(j.parse("").is_err());

    // Allow empty input.
    let jopt = parser(|o| o.require_value = false);
    assert_eq!(parsed(&jopt, ""), "null");
    assert_eq!(parsed(&jopt, "  // nothing\n/* here */"), "null");
}

/// Both ports site the two no-value errors at the start of the source,
/// where the canonical raises them before the lexer has a point to
/// report and leaves `row` and `col` undefined. The CODE agrees, and
/// that is what `../test/spec/options.tsv` pins in all three runtimes;
/// the POSITION is what diverges, and no fixture column carries it.
/// This is the pin for the RUST column of that entry in
/// `../DIVERGENCE.md`; `the-no-value-errors-carry-no-position` in
/// `ts/test/json5.test.ts` and `TestTheNoValueErrorsCarryAPosition` in
/// `go/json5_test.go` pin the other two.
#[test]
fn the_no_value_errors_carry_a_position() {
    let j = make();
    for (src, want) in [("//", "json5_no_value"), ("", "json5_empty")] {
        let error = parse_with(&j, src).expect_err("refused");
        assert_eq!(
            (error.code.as_str(), error.row, error.col),
            (want, 1, 1),
            "{src:?}"
        );
    }
}

// A hash-comment-only source with `require_value` OFF was a recorded
// divergence until 2026-09-21: the canonical's no-value scan knew only
// the two slash comment forms, so `#` counted as the start of a value,
// the source reached the rules, and the canonical fell out with
// `undefined` where this port and Go answered the declared empty
// result. The canonical's scan is told which comment forms the
// configuration has now, from its `requireValue`-OFF branch only, so all
// three answer null and the inputs are shared fixture rows in
// `../../test/spec/options.tsv` rather than a pin for one column here.
// `has_value` here takes the same flag, so both runtimes that have the
// short-circuit reach the result by the same route; measured before and
// after, this port's answer was null either way.

#[test]
fn non_strict_options() {
    let js = parser(|o| {
        o.octal = true;
        o.binary = true;
        o.number_separator = true;
    });
    assert_eq!(parsed(&js, "0o17"), "15");
    assert_eq!(parsed(&js, "0b101"), "5");
    assert_eq!(parsed(&js, "1_000"), "1000");

    let jnh = parser(|o| o.hex = false);
    assert_eq!(code(&jnh, "0x1F"), "unexpected");
}

#[test]
fn strict_value_toggle() {
    // With strictValue disabled, bare words parse as text strings
    // (jsonic's default text fallback).
    let j = parser(|o| o.strict_value = false);
    assert_eq!(parsed(&j, "foo"), r#""foo""#);
}

#[test]
fn json5_spec_example() {
    let j = make();
    let src = "{
      // comments
      unquoted: 'and you can quote me on that',
      singleQuotes: 'I can use \"double quotes\" here',
      lineBreaks: \"Look, Mom! \\
No \\\\n's!\",
      hexadecimal: 0xdecaf,
      leadingDecimalPoint: .8675309, andTrailing: 8675309.,
      positiveSign: +1,
      trailingComma: 'in objects', andIn: ['arrays',],
      \"backwardsCompatible\": \"with JSON\",
    }";
    assert_eq!(
        parsed(&j, src),
        concat!(
            r#"{"unquoted":"and you can quote me on that","#,
            r#""singleQuotes":"I can use \"double quotes\" here","#,
            r#""lineBreaks":"Look, Mom! No \\n's!","hexadecimal":912559,"#,
            r#""leadingDecimalPoint":0.8675309,"andTrailing":8675309,"positiveSign":1,"#,
            r#""trailingComma":"in objects","andIn":["arrays"],"backwardsCompatible":"with JSON"}"#
        )
    );
}

#[test]
fn json_is_json5() {
    let j = make();
    for src in [
        "{}",
        "[]",
        r#"{"a":1,"b":"two","c":null,"d":true,"e":false}"#,
        r#"[1,2.5,-3,1e10,"s",null,true,false]"#,
        r#"{"nested":{"list":[1,{"x":null}]}}"#,
    ] {
        // Compared in the fixture data model, where every number is an
        // f64 as in JSON.parse, so `1` and `1.0` are one value.
        let want = tabnas_support::parse_expect(src).expect("valid JSON");
        let got = to_value(&parse_with(&j, src).unwrap_or_else(|error| panic!("{src:?}: {error}")));
        assert!(
            tabnas_support::equal_value(&got, &want),
            "{src:?}: {}",
            tabnas_support::format_value(&got)
        );
    }
}

// --- Keys: decoded, not just validated (test/spec/keys.tsv pins the
// --- table; this pins the API detail that the decoded name is the key)

#[test]
fn unquoted_keys_are_decoded() {
    let j = make();
    let value = parse_with(&j, r"{sigΣma:1, A:2}").expect("it parses");
    let tabnas::Value::Object(map) = value else {
        panic!("not an object: {value:?}");
    };
    let keys: Vec<&str> = map.keys().map(String::as_str).collect();
    assert_eq!(keys, ["sigΣma", "A"]);
}

// --- The API surface -------------------------------------------------

#[test]
fn options_round_trip_through_the_plugin_bag() {
    let options = Json5Options {
        hash_comment: true,
        require_value: false,
        ..Default::default()
    };
    assert_eq!(Json5Options::from_value(&options.to_value()), options);

    // A key the bag does not carry keeps its default, as in Go.
    let partial = Json5Options::from_json(&serde_json::json!({ "octal": true }));
    assert_eq!(
        partial,
        Json5Options {
            octal: true,
            ..Default::default()
        }
    );
    // As does a key of the wrong type.
    let odd = Json5Options::from_json(&serde_json::json!({ "hex": "no" }));
    assert_eq!(odd, Json5Options::default());
}

#[test]
fn the_plugin_installs_through_use_plugin_and_records_its_options() {
    let mut parser = tabnas_jsonic::make();
    let overrides = Json5Options {
        backtick_string: true,
        ..Default::default()
    };
    parser
        .use_plugin(plugin(), Some(overrides.to_value()))
        .expect("the plugin installs");
    assert_eq!(parsed(&parser, "`x`"), r#""x""#);
    assert_eq!(code(&parser, ""), "json5_empty");

    // The engine's option bag carries the merged defaults.
    let bag = parser.plugin_options("json5").expect("the bag is recorded");
    assert_eq!(Json5Options::from_value(bag), overrides);
}

#[test]
fn the_plain_install_function_matches_the_plugin() {
    let mut direct = tabnas_jsonic::make();
    json5(&mut direct, &Json5Options::default()).expect("the plugin installs");
    let through_make = make();
    for src in ["{a:1,}", "[1,2,]", "0x10", "Infinity", "'s'"] {
        assert_eq!(parsed(&direct, src), parsed(&through_make, src), "{src:?}");
    }
    assert_eq!(code(&direct, "foo"), code(&through_make, "foo"));
}

#[test]
fn parse_with_on_a_parser_without_the_plugin_is_a_plain_parse() {
    let jsonic = tabnas_jsonic::make();
    assert_eq!(parsed(&jsonic, "a:1"), r#"{"a":1}"#);
    assert_eq!(
        json(&parse_with(&jsonic, "").expect("jsonic accepts empty")),
        "undefined"
    );
}

#[test]
fn errors_carry_the_position() {
    let j = make();
    let error = parse_with(&j, "[1,\n  foo]").expect_err("bare text is rejected");
    assert_eq!(error.code, "unexpected");
    assert_eq!((error.row, error.col), (2, 3));
}

#[test]
fn a_string_line_continuation_is_stripped_inside_strings_only() {
    let j = make();
    assert_eq!(parsed(&j, "['a\\\nb', \"p\\\r\nq\"]"), r#"["ab","pq"]"#);
    assert!(parse_with(&j, "[1,\\\n2]").is_err());
    // A backslash does NOT continue a line comment.
    assert_eq!(parsed(&j, "// c\\\n1"), "1");
}

/// Where `src` fails, as (code, row, col, pos), through both entry points:
/// `parse_with` and the instance's own `Tabnas::parse`, which must agree,
/// since the continuation is read by the lexer.
fn error_at(parser: &Tabnas, src: &str) -> (String, usize, usize, usize) {
    let at = |result: Result<tabnas::Value, tabnas::TabnasError>| match result {
        Ok(value) => panic!("{src:?} parsed to {}", json(&value)),
        Err(error) => (error.code, error.row, error.col, error.pos),
    };
    let wrapped = at(parse_with(parser, src));
    assert_eq!(
        at(parser.parse(src)),
        wrapped,
        "{src:?}: parse_with and Tabnas::parse disagree"
    );
    wrapped
}

/// A string line continuation is read where it stands, so a string spans
/// the lines it is written on and every later token keeps the row, column
/// and offset the source gives it (tabnas/json5#80). Removing the
/// continuation from the source before lexing kept the value and put the
/// `@` below on row 2 in both of the first two cases, and the instance's
/// own parse refused a CRLF continuation outright. These are the issue's
/// table: row 3 after an LF and after a CRLF continuation, and row 2 in
/// the control, which has none. Mirrors
/// `a-line-continuation-keeps-every-later-position` in
/// `ts/test/json5.test.ts`.
#[test]
fn a_line_continuation_keeps_every_later_position() {
    let j = make();
    let unexpected = |row, col, pos| ("unexpected".to_string(), row, col, pos);
    assert_eq!(error_at(&j, "['a\\\nb',\n  @]"), unexpected(3, 3, 11));
    assert_eq!(error_at(&j, "['a\\\r\nb',\r\n  @]"), unexpected(3, 3, 13));
    assert_eq!(error_at(&j, "['ab',\n  @]"), unexpected(2, 3, 9));
}

/// A CRLF continuation reads exactly as an LF one: the same value, and the
/// same row and column for what follows it on the line after.
#[test]
fn a_crlf_continuation_reads_as_an_lf_one() {
    let j = make();
    for eol in ["\n", "\r\n"] {
        let src = format!("'a\\{eol}b'");
        assert_eq!(parsed(&j, &src), r#""ab""#, "{src:?}");
        let value = j
            .parse(&src)
            .unwrap_or_else(|error| panic!("Tabnas::parse({src:?}): {error}"));
        assert_eq!(json(&value), r#""ab""#, "{src:?}");
        let (code, row, col, _) = error_at(&j, &format!("['a\\{eol}b', @]"));
        assert_eq!((code.as_str(), row, col), ("unexpected", 2, 5), "{eol:?}");
    }
}

/// Only an odd run of backslashes escapes the line break. Two before a
/// CRLF are an escaped backslash and then a real line break, which a
/// string may not hold; three are an escaped backslash and a continuation.
#[test]
fn only_an_odd_run_of_backslashes_continues_a_line() {
    let j = make();
    let (code, row, col, _) = error_at(&j, "['a\\\\\r\nb']");
    assert_eq!((code.as_str(), row, col), ("unprintable", 1, 6));
    assert_eq!(parsed(&j, "['a\\\\\\\r\nb']"), r#"["a\\b"]"#);
    let (code, row, col, _) = error_at(&j, "['a\\\\\\\r\nb', @]");
    assert_eq!((code.as_str(), row, col), ("unexpected", 2, 5));
}

// --- The shared default parser ----------------------------------------

#[test]
fn parse_uses_a_shared_default_and_is_safe_across_threads() {
    assert_eq!(
        json(&parse("{a:[1,2,],b:0x10}").unwrap()),
        r#"{"a":[1,2],"b":16}"#
    );
    assert_eq!(parse("").unwrap_err().code, "json5_empty");

    let sources: Arc<Vec<&'static str>> = Arc::new(vec![
        "{a:1}",
        "[1,2,3,]",
        "'x'",
        "Infinity",
        "// c\n42",
        "{sig\\u03A3ma:1}",
    ]);
    let handles: Vec<_> = (0..8)
        .map(|_| {
            let sources = Arc::clone(&sources);
            thread::spawn(move || {
                for _ in 0..50 {
                    for src in sources.iter() {
                        parse(src).unwrap_or_else(|error| panic!("{src:?}: {error}"));
                    }
                }
            })
        })
        .collect();
    for handle in handles {
        handle.join().expect("a parsing thread panicked");
    }
}

// --- Line separators inside a string literal ---------------------------

/// U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR may appear
/// UNESCAPED inside a JSON5 string, where CR and LF may not (JSON5 5.2:
/// a `JSON5DoubleStringCharacter` is any `SourceCharacter` but a quote,
/// a backslash or a `LineTerminator`, plus `LineContinuation`, plus
/// U+2028 and U+2029). TypeScript and Go both accept them.
///
/// This engine asks `line.chars` alone for what a string may not hold,
/// and `line.chars` plus `line.fixed` everywhere a line can end, so the
/// plugin puts LS and PS in `line.fixed`. Carrying them in `line.chars`
/// instead, as TypeScript and Go do, made every one of these inputs
/// `unprintable` here.
///
/// The rows belong in `../test/spec/strings.tsv`, where all three
/// runtimes would execute them; they are pinned here because the pass
/// that found the defect may not write the shared fixtures.
#[test]
fn a_line_separator_is_legal_inside_a_string_but_still_ends_a_line() {
    let j = make();
    for (src, want) in [
        ("\"a\u{2028}b\"", "a\u{2028}b"),
        ("\"a\u{2029}b\"", "a\u{2029}b"),
        ("'a\u{2028}b'", "a\u{2028}b"),
        ("\"\u{2028}\"", "\u{2028}"),
    ] {
        match parse_with(&j, src) {
            Ok(tabnas::Value::String(got)) => assert_eq!(got, want, "{src:?}"),
            other => panic!("{src:?}: {other:?}"),
        }
    }
    // CR and LF are still forbidden unescaped.
    for src in ["\"a\nb\"", "\"a\rb\""] {
        assert_eq!(code(&j, src), "unprintable", "{src:?}");
    }
    // LS still ends a line comment and still bumps the row counter,
    // which is what `line.fixed` and `line.rowChars` are for.
    assert_eq!(parsed(&j, "//c\u{2028}1"), "1");
    assert_eq!(parsed(&j, "//c\u{2029}1"), "1");
    match parse_with(&j, "1\u{2028}2") {
        Err(error) => assert_eq!(
            (error.code.as_str(), error.row, error.col),
            ("unexpected", 2, 1)
        ),
        other => panic!("{other:?}"),
    }
}

// --- Recorded divergences the shared files cannot hold -----------------

/// A LONE SURROGATE escape survives in canonical TypeScript and folds to
/// U+FFFD here. Inherited from the engine, and from Rust itself: a
/// JavaScript string is UTF-16 and may hold an unpaired surrogate, while
/// a Rust `String` (and a Go `string`) is UTF-8 and cannot. The Go port
/// answers U+FFFD for the same inputs, so this is not a Rust-only
/// deviation; it is where the two UTF-8 ports stand together.
///
/// It is pinned HERE rather than in `../test/divergent.tsv` because that
/// register cannot express it. Its cells are JSON values, and every
/// runtime but TypeScript reads them with a UTF-8 JSON decoder that
/// folds `\ud800` to U+FFFD: a `ts` cell of `"\ud800"` and a `rust` cell
/// of `"�"` then MEAN the same thing to the Go and Rust halves,
/// which refuse the row as recording no divergence at all. Measured, not
/// assumed -- both halves were run against exactly that row. The shared
/// `test/spec` fixtures refuse such a cell outright:
/// `tabnas_support::lone_surrogate_at` exists to find it.
#[test]
fn a_lone_surrogate_folds_to_the_replacement_character() {
    let j = make();
    // Every row of the entry's table, so the Rust column is executed
    // whole. The reversed-halves row was missing until 2026-09-21: the
    // TypeScript and Go mirrors carried it and this one did not, so one
    // of the five figures rested on a hand measurement. Measured here:
    // U+FFFD U+FFFD, two folds.
    for (src, want) in [
        (r#""\uD800""#, "\u{FFFD}"),
        (r#""\uDFFF""#, "\u{FFFD}"),
        (r#""a\uD800b""#, "a\u{FFFD}b"),
        (r#""\uDE00\uD83D""#, "\u{FFFD}\u{FFFD}"),
    ] {
        match parse_with(&j, src) {
            Ok(tabnas::Value::String(got)) => assert_eq!(got, want, "{src:?}"),
            other => panic!("{src:?}: {other:?}"),
        }
    }

    // The control, on the same input the TypeScript and Go mirrors use
    // and the table records: a well-formed PAIR is ONE astral
    // character, not two folds.
    match parse_with(&j, "\"\u{1F600}\"") {
        Ok(tabnas::Value::String(got)) => {
            assert_eq!(got.chars().count(), 1);
            assert_eq!(got, "\u{1F600}");
        }
        other => panic!("{other:?}"),
    }
}

// An astral `IdentifierStart` opening an unquoted key, or unquoted
// text under `strictValue: false`, was a divergence until 2026-09-21:
// the canonical text check read one UTF-16 code unit and saw a high
// surrogate. It reads a code point now, so all three runtimes agree and
// the cases belong in the shared fixtures rather than in a Rust-only
// test: five astral letters opening a key in `../test/spec/keys.tsv`,
// the two `strictValue: false` rows in `../test/spec/options.tsv`, and
// an astral NON-letter control beside each.

// --- The inherited nesting budget --------------------------------------

/// Nesting is BOUNDED here and unbounded in TypeScript and Go. The
/// budget is jsonic's, inherited by building on `tabnas_jsonic::make()`;
/// this plugin's own grammar document does not name `parse.budget`, and
/// installing it must not drop what jsonic set. The boundary is pinned
/// so that a change is a decision rather than a surprise, and so that
/// the figure in `../DIVERGENCE.md` stays true. A Rust-only divergence
/// cannot be a register row: the TypeScript and Go halves each compare
/// their own column against one other port's and fail a row whose two
/// columns agree, so this asserts the RUST side alone.
///
/// The bound is for the CALLER's stack, not the parse loop: the engine's
/// `Value` walks its own nesting in `to_json()`, and again in the
/// derived drop it has no iterative replacement for, both outside this
/// crate and both one frame per level.
///
/// The accepted depth is WALKED to its floor, not merely parsed. The
/// entry's Rust column reads "127 arrays" and "127 objects", and a
/// regression that accepted the document and truncated the value would
/// have kept an `unwrap()` here green while that figure went false. The
/// TypeScript and Go columns walk their trees for the same reason.
#[test]
fn nesting_is_capped_at_the_budget_jsonic_installs() {
    const LIMIT: usize = 127;
    let j = make();
    for (open, close, mid) in [("[", "]", ""), ("{a:", "}", "1")] {
        let at = |n: usize| format!("{}{mid}{}", open.repeat(n), close.repeat(n));
        let accepted =
            parse_with(&j, &at(LIMIT)).unwrap_or_else(|error| panic!("{LIMIT} levels: {error}"));
        let mut level = 0;
        let mut node = accepted;
        loop {
            let next = match &node {
                tabnas::Value::Array(items) if !items.is_empty() => items[0].clone(),
                tabnas::Value::Object(map) => match map.get("a") {
                    Some(next) => next.clone(),
                    None => break,
                },
                _ => break,
            };
            level += 1;
            node = next;
        }
        // The innermost `[]` is empty, so the array walk stops one level
        // short of the bracket count; the object walk reaches the scalar.
        let want = if mid.is_empty() { LIMIT - 1 } else { LIMIT };
        assert_eq!(level, want, "{LIMIT} levels of {open}");
        if !mid.is_empty() {
            assert_eq!(node, tabnas::Value::Number(1.0), "{LIMIT} levels of {open}");
        }
        match parse_with(&j, &at(LIMIT + 1)) {
            Err(error) => assert_eq!(error.code, "cancel", "{} levels", LIMIT + 1),
            Ok(value) => panic!("{} levels parsed: {}", LIMIT + 1, json(&value)),
        }
    }
    // Deeper still is refused rather than run, so no caller ever holds a
    // tree too deep to drop.
    match parse_with(&j, &"[".repeat(10_000)) {
        Err(error) => assert_eq!(error.code, "cancel"),
        Ok(value) => panic!("10000 levels parsed: {}", json(&value)),
    }
}

// --- Base-prefixed integers round once ---------------------------------

/// The exact IEEE-754 bits, because a decimal expectation cannot show
/// the defect this pins: a digit-by-digit floating-point fold lands one
/// unit in the last place away from the correctly rounded value, and
/// both spellings print alike at many digits. `test/spec/numbers.tsv`
/// carries the same literals as shared rows; this is the bit-level
/// statement of what those rows mean, plus the ties the fixture would
/// make unreadable.
///
/// The expectations are ECMAScript's: `Number(BigInt(literal))`, which
/// is what `parseInt` on the digits produces and so what the canonical
/// TypeScript port returns. Verified against node over 4,000 random
/// literals in all three bases.
#[test]
fn wide_base_prefixed_literals_round_once_from_the_exact_integer() {
    let j = make();
    let bits = |src: &str| match parse_with(&j, src) {
        Ok(tabnas::Value::Number(got)) => got.to_bits(),
        other => panic!("{src:?}: {other:?}"),
    };

    // The reported case. The fold answered 0x43a4de5ef1e9f37e.
    assert_eq!(bits("0Xa6f2f78f4f9bf44"), 0x43a4_de5e_f1e9_f37f);
    assert_eq!(bits("0xa6f2f78f4f9bf44"), 0x43a4_de5e_f1e9_f37f);
    assert_eq!(bits("-0Xa6f2f78f4f9bf44"), 0xc3a4_de5e_f1e9_f37f);
    assert_eq!(bits("+0xa6f2f78f4f9bf44"), 0x43a4_de5e_f1e9_f37f);

    // Exactly representable, so nothing rounds.
    assert_eq!(bits("0x1fffffffffffff"), 9_007_199_254_740_991f64.to_bits());

    // Ties go to the even mantissa: 2^53+1 rounds down, 2^53+3 rounds up.
    assert_eq!(bits("0X20000000000001"), 9_007_199_254_740_992f64.to_bits());
    assert_eq!(bits("0X20000000000003"), 9_007_199_254_740_996f64.to_bits());

    // Wider than a u128, so the tail only contributes a sticky bit.
    assert_eq!(bits("0Xffffffffffffffffffffffffffffffffff"), {
        let two: f64 = 2.0;
        two.powi(136).to_bits()
    });
    assert_eq!(bits("0X10000000000000000000000000000000001"), {
        let two: f64 = 2.0;
        two.powi(136).to_bits()
    });

    // Past the double range is infinity, as `Number` of the bigint is.
    let wide = format!("0x{}", "f".repeat(300));
    assert_eq!(bits(&wide), f64::INFINITY.to_bits());

    // Leading zeros are not significant, and neither is a `0` literal.
    assert_eq!(
        bits("0X0000000000000000000000000000000000001"),
        1f64.to_bits()
    );
    assert_eq!(bits("0x0"), 0f64.to_bits());

    // The same conversion serves octal and binary under their options.
    let jo = parser(|o| {
        o.octal = true;
        o.binary = true;
    });
    let bits_o = |src: &str| match parse_with(&jo, src) {
        Ok(tabnas::Value::Number(got)) => got.to_bits(),
        other => panic!("{src:?}: {other:?}"),
    };
    assert_eq!(bits_o("0o46754573436475757744"), 0x43a3_7b2f_71e9_efc0);
    assert_eq!(
        bits_o("0b1010011011110010111101111000111101001111100110111111010001000101"),
        0x43e4_de5e_f1e9_f37f
    );

    // And with the `uppercaseHex` value definition rather than the number
    // lexer, which is the path `hex: false` leaves in place.
    let jn = parser(|o| o.hex = false);
    match parse_with(&jn, "0Xa6f2f78f4f9bf44") {
        Ok(tabnas::Value::Number(got)) => assert_eq!(got.to_bits(), 0x43a4_de5e_f1e9_f37f),
        other => panic!("{other:?}"),
    }
}

/// An unquoted key is an ECMAScript 5.1 `IdentifierName`, whose
/// `IdentifierStart` is a `UnicodeLetter`: "any character in the Unicode
/// categories Lu, Ll, Lt, Lm, Lo, or Nl". ES5.1 names no Unicode
/// VERSION, so each runtime answers from the tables its platform ships,
/// and the three platforms ship three different versions. This crate
/// reads `\p{L}` and `\p{Nl}` through the `regex` crate, whose tables
/// are Unicode 16.0; Go reads `unicode.IsLetter`, which is 15.0 in Go
/// 1.24; and the canonical reads a JavaScript regular expression, so it
/// gets whatever Unicode the host's ICU carries, 17.0 on Node 22.
///
/// The consequence is recorded in `../DIVERGENCE.md` under "Unquoted
/// keys follow each platform's Unicode tables", with the measured table.
/// This test is that entry's Rust column, and it is a test rather than a
/// row of `../test/divergent.tsv` because a register cell states what a
/// PORT does, while these answers change with the toolchain a port is
/// built with: the same `rs/src/lib.rs` accepts U+088F the day `regex`
/// ships Unicode 17, and the same `ts/src/json5.ts` stops accepting it
/// on a Node whose ICU is older. A register row would then report a
/// repair or a regression where neither happened.
///
/// It is expected to go red when this crate's tables move, and that is
/// the point: re-measure the entry and correct the table rather than
/// widening this test.
#[test]
fn unquoted_keys_follow_this_crates_unicode_tables() {
    let j = make();

    // DELEGATION, the half the TypeScript and Go columns also assert:
    // the key opens exactly when this crate's own letter test says the
    // character is a letter. A port that froze a character list instead
    // of asking its platform fails here.
    let letter = regex::Regex::new(r"^[\p{L}\p{Nl}]$").expect("a literal pattern");
    for ch in ['\u{00E9}', '\u{1C89}', '\u{088F}', '\u{1F600}'] {
        let want = letter.is_match(ch.encode_utf8(&mut [0; 4]));
        let start = format!("{{{ch}:1}}");
        let part = format!("{{a{ch}:1}}");
        assert_eq!(
            parse_with(&j, &start).is_ok(),
            want,
            "U+{:04X} as a key start",
            ch as u32
        );
        assert_eq!(
            parse_with(&j, &part).is_ok(),
            want,
            "U+{:04X} as a key part",
            ch as u32
        );
    }

    // The controls, which no Unicode version moves. U+00E9 has been a
    // letter (Ll) since Unicode 1.0, and U+1F600 GRINNING FACE is So in
    // every version, so these two hold the test to the identifier rule
    // rather than to a table edition, and they keep the loop above from
    // passing vacuously on four characters that all answer alike.
    assert_eq!(parsed(&j, "{\u{00E9}:1}"), "{\"\u{00E9}\":1}");
    assert!(parse_with(&j, "{\u{1F600}:1}").is_err());

    // U+1C89 CYRILLIC SMALL LETTER TJE became a letter in Unicode 16.0.
    // This crate's tables have it, so the key opens here and in the
    // canonical; Go's 15.0 tables do not, and Go rejects it.
    assert_eq!(parsed(&j, "{\u{1C89}:1}"), "{\"\u{1C89}\":1}");
    assert_eq!(parsed(&j, "{a\u{1C89}:1}"), "{\"a\u{1C89}\":1}");

    // U+088F ARABIC became a letter in Unicode 17.0. The canonical
    // accepts it on a host whose ICU carries 17.0; this crate's 16.0
    // tables do not, so the key is refused here, as it is in Go.
    assert!(parse_with(&j, "{\u{088F}:1}").is_err());
    assert!(parse_with(&j, "{a\u{088F}:1}").is_err());
}