quickjs-pure 0.17.5

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
//! `JSON`.
//!
//! `JSON.stringify` is specified in terms of a *serialisation state* that the
//! indentation threads through, and the output is compared byte for byte by the
//! reference test suite — including the trailing-newline-free format with `indent`
//! and the exact placement of `": "`. That is why the writer below is explicit about
//! separators rather than leaning on a generic pretty-printer.
//!
//! `JSON.parse` accepts the strict JSON grammar; the reference also accepts a few
//! extensions, but nothing here depends on them.

use crate::builtins::{arg, define_method, install_tag};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, Property, PropertyKey};
use crate::value::{Value, number_to_string};
use js_gc::Gc;

/// Install `JSON`.
pub fn install(interp: &mut Interp<'_>) {
    let object_proto = interp.realm.object_proto.clone();
    let json = interp.new_object(Some(object_proto));
    // §21.3: `Object.prototype.toString.call(JSON)` is `[object JSON]`.
    install_tag(&json, "JSON", interp);
    define_method(&json, "stringify", 3, stringify, interp);
    define_method(&json, "parse", 2, parse, interp);
    // The `json-parse-with-source` proposal's other half. Both were absent, and the pair was
    // filed in the test262 skip list under "engine does not have the feature" — which was
    // true of these two *methods* and false of the `context.source` argument to a reviver,
    // so the skip hid 21 cases that had two different causes (`docs/test262-status.md` §4.44).
    define_method(&json, "rawJSON", 1, raw_json, interp);
    define_method(&json, "isRawJSON", 1, is_raw_json, interp);
    let global = interp.realm.global.clone();
    global.define(
        "JSON",
        Property::with_attributes(Value::Object(json), true, false),
    );
}

// ---------------------------------------------------------------------------
// stringify
// ---------------------------------------------------------------------------

fn stringify(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = arg(args, 0);
    // The second argument restricts or rewrites what is serialised: a function is called for
    // every key, an array is the list of keys that survive. Ignoring it made
    // `JSON.stringify({a:1,b:2}, ["a"])` emit both keys.
    let replacer = Replacer::new(interp, &arg(args, 1))?;
    // §25.5.2 steps 5–9: the indent is a number of spaces or a string used verbatim, and a
    // **wrapper** is unwrapped first. Ignoring the wrapper arm meant
    // `JSON.stringify(x, null, new Number(2))` came out unindented
    // (`space-number-object`, `space-string-object`) and `new Number(1.5)` was not the two
    // spaces `ToIntegerOrInfinity` gives it (`space-number-float`).
    //
    // The wrapper is unwrapped with **`ToNumber` / `ToString`, not by reading its slot**:
    // `new Number(1)` whose `valueOf` answers `3` indents by three, and one whose `valueOf`
    // throws makes `JSON.stringify` throw (`space-number-object` asserts both).
    let space = arg(args, 2);
    let space = match &space {
        Value::Object(wrapper) => match interp.internal_get(wrapper, "_value") {
            Some(Value::String(_)) => {
                let text = interp.to_js_string(&space)?;
                match interp.string(text) {
                    Value::String(text) => Value::String(text),
                    _ => Value::Undefined,
                }
            }
            Some(Value::Int(_) | Value::Float(_)) => Value::Float(interp.to_js_number(&space)?),
            _ => Value::Undefined,
        },
        other => other.clone(),
    };
    let indent = match &space {
        Value::Int(_) | Value::Float(_) => {
            // `ToIntegerOrInfinity`, then `min(10, …)`.
            let count = interp.to_js_number(&space)?.trunc().clamp(0.0, 10.0) as usize;
            " ".repeat(count)
        }
        // The first ten **code units**, so an astral character counts as two.
        Value::String(text) => text
            .wtf8()
            .slice_units(0, 10)
            .to_string_lossy()
            .into_owned(),
        _ => String::new(),
    };
    let mut out = String::new();
    let mut stack: Vec<Gc<JsObject>> = Vec::new();
    let root = make_root_holder(interp, &value)?;
    match write_value(
        interp,
        &mut Writer {
            out: &mut out,
            indent: &indent,
            depth: 0,
            stack: &mut stack,
        },
        &root,
        &value,
        "",
        &replacer,
    )? {
        // `undefined`, a function and a symbol serialise to nothing at the top level.
        true => Ok(interp.string(out)),
        false => Ok(Value::Undefined),
    }
}

/// The `{"": value}` wrapper the spec puts around the root value.
///
/// A replacer function is called with this as `this` for the root, and `this[""]` is the
/// value — which is how a replacer that recurses through `this` gets its starting point.
fn make_root_holder(interp: &mut Interp<'_>, value: &Value) -> JsResult<Value> {
    let holder = interp.new_object(None);
    interp.set_property(&holder, "", value.clone())?;
    Ok(Value::Object(holder))
}

/// `JSON.stringify`'s `replacer` argument.
///
/// A function is called with the holder and the key; an array names the properties to keep.
/// Anything else (including `undefined`) is the identity.
enum Replacer {
    None,
    /// The function to call, and the raw value to pass as `this` (the holder).
    Function(Value),
    /// The keys to keep, in the order first seen.
    Keys(Vec<String>),
}

impl Replacer {
    fn new(interp: &mut Interp<'_>, value: &Value) -> JsResult<Replacer> {
        let Value::Object(object) = value else {
            return Ok(Replacer::None);
        };
        if object.is_callable() {
            return Ok(Replacer::Function(value.clone()));
        }
        if !object.is_array() {
            return Ok(Replacer::None);
        }
        // §25.5.2 step 4.a: `LengthOfArrayLike(replacer)` — `Get(replacer, "length")` then
        // `ToLength`, both script-visible. `array_length()` answers `None` for a **proxy**,
        // which made `JSON.stringify(x, new Proxy(["b"], {}))` emit `{}`.
        let length = match interp.get_property(object, "length")? {
            None | Some(Value::Undefined) => 0,
            Some(value) => {
                let number = interp.to_js_number(&value)?;
                if number.is_nan() || number <= 0.0 {
                    0
                } else {
                    number.min(9_007_199_254_740_991.0) as usize
                }
            }
        };
        let mut keys: Vec<String> = Vec::new();
        for index in 0..length {
            let Some(element) = interp.get_property(object, &index.to_string())? else {
                continue;
            };
            // 4.a.iv: a String contributes itself; a Number or BigInt is `ToString`'d; a
            // String/Number/BigInt **wrapper** is `ToString`'d as well. The wrapper arm was
            // missing, so `JSON.stringify({a: 2}, [new String("a")])` emitted `{}`.
            let text = match &element {
                Value::String(text) => text.to_string_lossy().to_string(),
                Value::Int(_) | Value::Float(_) | Value::BigInt(_) => {
                    interp.to_js_string(&element)?
                }
                Value::Object(wrapper) => match interp.internal_get(wrapper, "_value") {
                    Some(Value::String(_) | Value::Int(_) | Value::Float(_) | Value::BigInt(_)) => {
                        interp.to_js_string(&element)?
                    }
                    _ => continue,
                },
                _ => continue,
            };
            if !keys.contains(&text) {
                keys.push(text);
            }
        }
        Ok(Replacer::Keys(keys))
    }

    /// The `PropertyList` an array replacer builds, in its own order.
    ///
    /// `SerializeJSONObject` walks this list rather than the object's own keys, which is
    /// the only way `JSON.stringify({a:1,b:2,c:3}, ["c","b","a"])` can answer
    /// `{"c":3,"b":2,"a":1}` — filtering the object's keys kept insertion order
    /// (`replacer-array-order`).
    fn property_list(&self) -> Option<&[String]> {
        match self {
            Replacer::Keys(keys) => Some(keys),
            _ => None,
        }
    }

    /// `SerializeJSONProperty`'s replacer step: the function replaces the value.
    fn apply(
        &self,
        interp: &mut Interp<'_>,
        holder: &Value,
        value: &Value,
        key: &str,
    ) -> JsResult<Value> {
        let Replacer::Function(function) = self else {
            return Ok(value.clone());
        };
        interp.call_value(
            function.clone(),
            holder.clone(),
            vec![interp.string(key), value.clone()],
        )
    }
}

/// Serialise `value` into `out`. Returns whether anything was written, which is how
/// a top-level `undefined` becomes the value `undefined` rather than `"undefined"`.
///
/// `key` is the property name the value was read from, which `toJSON` receives; the
/// root value is passed the empty string, as the spec's wrapper object does.
/// The primitive inside a wrapper object, or the value unchanged.
///
/// `_value` is the slot this engine's `new Number(x)` and `Object(x)` fill in, so it is
/// the same thing the spec's internal slots carry.
fn unwrap_primitive_wrapper(interp: &Interp<'_>, value: &Value) -> Value {
    let Some(object) = value.as_object() else {
        return value.clone();
    };
    let Some(inner) = interp.internal_get(object, "_value") else {
        return value.clone();
    };
    // Only a box of a *primitive*: an ordinary object that happens to have `_value` must
    // keep serialising as an object.
    match inner {
        Value::Int(_) | Value::Float(_) | Value::String(_) | Value::Bool(_) | Value::BigInt(_) => {
            inner
        }
        _ => value.clone(),
    }
}

/// The verbatim JSON text of a `[[IsRawJSON]]` object, if that is what `object` is.
fn raw_json_text(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
    let marker = interp.internal_get(object, "_is_raw_json")?;
    if !marker.to_boolean() {
        return None;
    }
    let text = object.own_property("rawJSON")?.value?;
    Some(text.to_js_string())
}

/// Where the text is being written: the buffer, the indent unit and how deep the current
/// value sits. Grouped so `write_value` keeps a readable argument list.
struct Writer<'a> {
    out: &'a mut String,
    indent: &'a str,
    depth: usize,
    /// `SerializeJSONProperty`'s `stack`: the objects currently being serialised, root
    /// first. Meeting one twice means the value graph has a cycle, and the spec makes that
    /// a `TypeError` rather than an attempt to describe the loop.
    ///
    /// Without this the recursion below ran off the *Rust* stack and aborted the whole
    /// process — no JS-level limit could stop it, because the recursion was in the host.
    stack: &'a mut Vec<Gc<JsObject>>,
}

fn write_value(
    interp: &mut Interp<'_>,
    writer: &mut Writer<'_>,
    holder: &Value,
    value: &Value,
    key: &str,
    replacer: &Replacer,
) -> JsResult<bool> {
    // `out` and `stack` are separate fields, so borrowing both at once is fine.
    let Writer {
        out,
        indent,
        depth,
        stack,
    } = writer;
    let (indent, depth) = (*indent, *depth);
    // The array form does **not** filter here: its `PropertyList` decides which keys
    // `SerializeJSONObject` walks at all (see `write_object`), while an *array* serialises
    // every position regardless. Filtering by key at this level made
    // `JSON.stringify([1, {}], [])` emit `[null,null]`.
    // A value carrying a `toJSON` method is replaced by whatever that returns, and
    // the replacement is not asked for `toJSON` again. This is how a `Date`
    // serialises to its ISO string.
    let value = &call_to_json(interp, value, key)?;
    // A replacer *function* receives the value after `toJSON` and may replace it outright.
    // `this` is the holder — the object or array the value was read from — because a
    // replacer commonly reads sibling properties through `this[key]`.
    let value = &replacer.apply(interp, holder, value, key)?;
    // A wrapper object serialises as the primitive it wraps: `JSON.stringify(Object(1))`
    // is `"1"`, not `"{}"`. SerialiseJSONProperty unwraps `[[NumberData]]`,
    // `[[StringData]]`, `[[BooleanData]]` and `[[BigIntData]]` before looking at the
    // object's enumerable keys, and a wrapper has none of its own — which is why skipping
    // the step printed an empty object.
    let value = &unwrap_primitive_wrapper(interp, value);
    // A value carrying `[[IsRawJSON]]` is emitted verbatim, after `toJSON` and the replacer
    // have had their say — `JSON.stringify({toJSON: () => JSON.rawJSON(3)})` is `"3"`, and
    // a replacer that returns a rawJSON object gets the same treatment.
    if let Value::Object(object) = value
        && let Some(text) = raw_json_text(interp, object)
    {
        out.push_str(&text);
        return Ok(true);
    }
    match value {
        // A symbol serialises to nothing, exactly like `undefined`: `JSON.stringify`
        // drops it from an object and answers `undefined` for it at the top level.
        // A bigint has no JSON form, and the spec makes that an error rather than a
        // silent omission — losing a number is not the same as losing `undefined`.
        Value::BigInt(_) => Err(interp.type_error("BigInt value can't be serialized in JSON")),
        Value::Undefined
        | Value::Symbol(_)
        | Value::Uninitialized
        | Value::Hole
        | Value::CatchOffset(_)
        | Value::ReturnAddress(_) => Ok(false),
        Value::Null => {
            out.push_str("null");
            Ok(true)
        }
        Value::Bool(value) => {
            out.push_str(if *value { "true" } else { "false" });
            Ok(true)
        }
        Value::Int(_) | Value::Float(_) => {
            let number = value.to_number();
            // `NaN` and the infinities serialise as `null`.
            if number.is_finite() {
                out.push_str(&number_to_string(number));
            } else {
                out.push_str("null");
            }
            Ok(true)
        }
        Value::String(text) => {
            write_string(text.wtf8(), out);
            Ok(true)
        }
        Value::Object(object) => {
            if object.is_callable() {
                return Ok(false);
            }
            // `SerializeJSONProperty`: an object already on the stack is a cycle, and the
            // spec turns that into a `TypeError`. The comparison is by identity, so two
            // separate but equal objects are fine — only a genuine loop is rejected.
            //
            // Checked here rather than in `write_array`/`write_object` so both share one
            // rule, and *before* descending so a self-referential root is caught at depth 1
            // instead of after the first level of recursion.
            if stack.iter().any(|seen| seen.ptr_eq(object)) {
                return Err(interp.type_error("circular reference"));
            }
            stack.push(object.clone());
            let result = if object.is_array() {
                write_array(
                    interp,
                    &mut Writer {
                        out,
                        indent,
                        depth,
                        stack,
                    },
                    object,
                    replacer,
                )
            } else {
                write_object(
                    interp,
                    &mut Writer {
                        out,
                        indent,
                        depth,
                        stack,
                    },
                    object,
                    replacer,
                )
            };
            stack.pop();
            result?;
            Ok(true)
        }
    }
}

/// `SerializeJSONProperty`'s `toJSON` step, applied once.
fn call_to_json(interp: &mut Interp<'_>, value: &Value, key: &str) -> JsResult<Value> {
    let Value::Object(object) = value else {
        return Ok(value.clone());
    };
    let Some(method) = interp.get_property(object, "toJSON")? else {
        return Ok(value.clone());
    };
    if !matches!(&method, Value::Object(function) if function.is_callable()) {
        return Ok(value.clone());
    }
    interp.call_value(method, value.clone(), vec![interp.string(key)])
}

fn write_array(
    interp: &mut Interp<'_>,
    writer: &mut Writer<'_>,
    array: &Gc<JsObject>,
    replacer: &Replacer,
) -> JsResult<()> {
    let Writer {
        out,
        indent,
        depth,
        stack,
    } = writer;
    let (indent, depth) = (*indent, *depth);
    // `LengthOfArrayLike`. A plain array answers from its slot; a **proxy** over one has no
    // slot of its own, so the length comes through `[[Get]]`, which forwards to the target —
    // reading `array_length()` and defaulting to 0 made
    // `JSON.stringify(new Proxy([0,1], {}))` emit `[]` (`value-array-proxy`).
    let length = match array.array_length() {
        Some(length) => length,
        None => match interp.get_property(array, "length")? {
            None | Some(Value::Undefined) => 0,
            Some(value) => {
                let number = interp.to_js_number(&value)?;
                if number.is_nan() || number <= 0.0 {
                    0
                } else {
                    number.min(9_007_199_254_740_991.0) as usize
                }
            }
        },
    };
    if length == 0 {
        out.push_str("[]");
        return Ok(());
    }
    out.push('[');
    for index in 0..length {
        if index > 0 {
            out.push(',');
        }
        newline(out, indent, depth + 1);
        // `[[Get]]`, not the element vector: an accessor defined on an index lives in the
        // property table and the slot it shadows is a hole, so reading the vector directly
        // printed `null` for `Object.defineProperty(a, "0", {get})`.
        let element = match array.array_get(index) {
            Some(Value::Hole) | None => interp
                .get_property_key(array, &PropertyKey::from(index.to_string()))?
                .unwrap_or(Value::Undefined),
            Some(value) => value,
        };
        // A hole or an unserialisable element becomes `null`, because an array's
        // positions are part of its meaning.
        if !write_value(
            interp,
            &mut Writer {
                out,
                indent,
                depth: depth + 1,
                stack,
            },
            &Value::Object(array.clone()),
            &element,
            &index.to_string(),
            replacer,
        )? {
            out.push_str("null");
        }
    }
    newline(out, indent, depth);
    out.push(']');
    Ok(())
}

fn write_object(
    interp: &mut Interp<'_>,
    writer: &mut Writer<'_>,
    object: &Gc<JsObject>,
    replacer: &Replacer,
) -> JsResult<()> {
    let Writer {
        out,
        indent,
        depth,
        stack,
    } = writer;
    let (indent, depth) = (*indent, *depth);
    // Enumerable own keys in the spec's order, skipping keys whose values do not
    // serialise (a function-valued property is omitted, not `null`).
    //
    // Through `[[OwnPropertyKeys]]` and `[[GetOwnProperty]]`, so a proxy serialises as
    // its handler describes it: reading the property table directly made
    // `JSON.stringify(proxy)` emit `{}` for every proxy.
    let mut keys: Vec<crate::object::PropertyKey> = Vec::new();
    // With an array replacer the walk order is the replacer's, and an own key it does not
    // name is never visited at all.
    if let Some(list) = replacer.property_list() {
        for name in list {
            keys.push(crate::object::PropertyKey::from(name.as_str()));
        }
    }
    for key in if replacer.property_list().is_some() {
        Vec::new()
    } else {
        interp.object_own_property_keys(object)?
    } {
        if key.is_symbol() {
            // A symbol-keyed property is invisible to `JSON.stringify`.
            continue;
        }
        let enumerable = interp
            .object_get_own_property(object, &key)?
            .is_some_and(|property| property.enumerable);
        if enumerable {
            keys.push(key);
        }
    }
    let mut written = 0usize;
    let mut body = String::new();
    for key in keys {
        // Two views of the same key: the replacer's plumbing takes a `&str` (it compares
        // against the replacer array and hands the key to a user function), while the
        // emitted JSON must keep the key's own code units — a key may hold an unpaired
        // surrogate, and flattening it here would print a different property name.
        let key_text = key.as_str().unwrap_or_default().to_string();
        let key_json = key.as_wtf8().cloned().unwrap_or_default();
        let Some(value) = interp.get_property_key(object, &key)? else {
            continue;
        };
        let mut piece = String::new();
        // Render the value first so an unrepresentable one can be skipped whole.
        if !write_value(
            interp,
            &mut Writer {
                out: &mut piece,
                indent,
                depth: depth + 1,
                stack,
            },
            &Value::Object(object.clone()),
            &value,
            &key_text,
            replacer,
        )? {
            continue;
        }
        if written > 0 {
            body.push(',');
        }
        newline(&mut body, indent, depth + 1);
        let mut escaped = String::new();
        write_string(&key_json, &mut escaped);
        body.push_str(&escaped);
        body.push(':');
        if !indent.is_empty() {
            body.push(' ');
        }
        body.push_str(&piece);
        written += 1;
    }
    if written == 0 {
        out.push_str("{}");
        return Ok(());
    }
    out.push('{');
    out.push_str(&body);
    newline(out, indent, depth);
    out.push('}');
    Ok(())
}

/// Emit the indentation for one level, or nothing when not pretty-printing.
fn newline(out: &mut String, indent: &str, depth: usize) {
    if indent.is_empty() {
        return;
    }
    out.push('\n');
    for _ in 0..depth {
        out.push_str(indent);
    }
}

/// Write `text` as a JSON string literal.
///
/// The escapes are the spec's twenty-odd: the two mandatory ones, the two that are
/// required for well-formed JSON in a script (`\u2028`/`\u2029`), and control
/// characters below `0x20` as `\u00XX`.
fn write_string(text: &crate::value::Wtf8, out: &mut String) {
    out.push('"');
    // Code *units*, because a string may hold an unpaired surrogate and JSON requires one
    // to be written as `\udXXX` rather than dropped or replaced by U+FFFD. A valid pair is
    // folded back into its astral character, which is what the reference prints and what
    // keeps well-formed text readable in the output.
    let units = text.to_units();
    let mut index = 0;
    while index < units.len() {
        let unit = units[index];
        if (0xD800..0xDC00).contains(&unit)
            && let Some(&low) = units.get(index + 1)
            && (0xDC00..0xE000).contains(&low)
        {
            let code = 0x10000 + ((u32::from(unit) - 0xD800) << 10) + (u32::from(low) - 0xDC00);
            write_char(char::from_u32(code).unwrap_or('\u{fffd}'), out);
            index += 2;
            continue;
        }
        if (0xD800..0xE000).contains(&unit) {
            out.push_str(&format!("\\u{unit:04x}"));
            index += 1;
            continue;
        }
        write_char(char::from_u32(u32::from(unit)).unwrap_or('\u{fffd}'), out);
        index += 1;
    }
    out.push('"');
}

/// One non-surrogate code unit's escape.
fn write_char(character: char, out: &mut String) {
    match character {
        '"' => out.push_str("\\\""),
        '\\' => out.push_str("\\\\"),
        '\n' => out.push_str("\\n"),
        '\r' => out.push_str("\\r"),
        '\t' => out.push_str("\\t"),
        '\u{8}' => out.push_str("\\b"),
        '\u{c}' => out.push_str("\\f"),
        c if (c as u32) < 0x20 => {
            out.push_str(&format!("\\u{:04x}", c as u32));
        }
        c => out.push(c),
    }
}

/// `JSON.rawJSON(value)` — a value whose JSON spelling is given verbatim.
///
/// The point is round-tripping what a JS number cannot hold: `JSON.stringify` of
/// `JSON.rawJSON("9007199254740993")` emits exactly those digits instead of the
/// `9007199254740992` the double rounds to.
///
/// The argument must stringify to a single JSON **primitive**. `"[1]"`, `"{}"` and `"1 2"`
/// are all `SyntaxError`s — "a parser accepted this text" is weaker than the spec, which
/// asks for exactly one primitive parse node.
fn raw_json(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToString` first, so a symbol is a `TypeError` (from the conversion) rather than a
    // `SyntaxError` about the text it never produced.
    let text = interp.checked_to_string(&arg(args, 0))?;
    if text.is_empty() || !is_json_primitive_text(&text) {
        return Err(crate::interp::Signal::Throw(
            interp.make_error("SyntaxError", "invalid JSON primitive"),
        ));
    }
    // `OrdinaryObjectCreate(null)`: a data key called `toString` must not collide with a
    // method, and the suite asserts the prototype is `null` and that `rawJSON` is the only
    // own property.
    let object = interp.new_object(None);
    object.define(
        "rawJSON",
        Property::with_attributes(interp.string(text), true, true),
    );
    // Not a visible property: `[[IsRawJSON]]` has to be unforgeable, or
    // `JSON.isRawJSON({rawJSON: "123"})` would answer `true`.
    interp.internal_set(&object, "_is_raw_json", Value::Bool(true));
    Ok(Value::Object(object))
}

/// Whether `text` is exactly one JSON primitive: a number, a string, `true`, `false` or
/// `null`, with no surrounding whitespace.
///
/// Reuses the real parser rather than a hand-rolled accept/reject, so `"1e"`, `"01"` and
/// `"\u12"` are rejected for the same reasons `JSON.parse` rejects them. The extension flag
/// is off: `rawJSON(Infinity)` must be a `SyntaxError`.
fn is_json_primitive_text(text: &str) -> bool {
    let mut parser = Parser {
        bytes: text.as_bytes(),
        text,
        position: 0,
        ext: false,
        // No reviver can ever see this tree, so there is nothing to record.
        track: false,
        last_span: (0, 0),
    };
    json_primitive_text(&mut parser)
}

/// The parser half of [`is_json_primitive_text`], split out so it can run without an
/// `Interp`.
///
/// `Parser::value_inner` needs an `Interp` for the string and container cases. A scan that
/// answers the same question without allocating is 30 lines and avoids the interpreter
/// entirely, so it cannot run a getter or grow the heap.
fn json_primitive_text(parser: &mut Parser<'_>) -> bool {
    let text = parser.text;
    if text.is_empty() || text.trim() != text {
        return false;
    }
    // A string literal: quoted, and the closing quote is the last byte.
    if text.starts_with('"') {
        if !text.ends_with('"') || text.len() < 2 {
            return false;
        }
        return valid_json_string(&text[1..text.len() - 1]);
    }
    if text == "true" || text == "false" || text == "null" {
        return true;
    }
    parser.position = 0;
    parser.number().is_ok() && parser.position == text.len()
}

/// Whether `body` is a run of JSON string content: no raw control characters, no lone
/// backslash, and every `\u` escape followed by four hex digits.
fn valid_json_string(body: &str) -> bool {
    let bytes = body.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'"' => return false,
            b'\\' => {
                index += 1;
                match bytes.get(index) {
                    Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => index += 1,
                    Some(b'u') => {
                        index += 1;
                        for _ in 0..4 {
                            match bytes.get(index) {
                                Some(byte) if byte.is_ascii_hexdigit() => index += 1,
                                _ => return false,
                            }
                        }
                    }
                    _ => return false,
                }
            }
            byte if byte < 0x20 => return false,
            byte => index += utf8_len(byte),
        }
    }
    true
}

fn utf8_len(first: u8) -> usize {
    match first {
        0x00..=0x7f => 1,
        0xc0..=0xdf => 2,
        0xe0..=0xef => 3,
        _ => 4,
    }
}

/// `JSON.isRawJSON(value)` — true only for an object carrying `[[IsRawJSON]]`.
fn is_raw_json(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let is_raw = match arg(args, 0) {
        Value::Object(object) => interp
            .internal_get(&object, "_is_raw_json")
            .is_some_and(|marker| marker.to_boolean()),
        _ => false,
    };
    Ok(Value::Bool(is_raw))
}

// ---------------------------------------------------------------------------
// parse
// ---------------------------------------------------------------------------

/// Parse `text`, either as RFC 8259 JSON or in the extended dialect.
///
/// The extended dialect is what the reference calls `JS_PARSE_JSON_EXT`: the same parser
/// with a flag, not a separate parser and not a pre-processing pass. It is exposed to
/// scripts only through `std.parseExtJSON`, so `JSON.parse` stays strict.
pub fn parse_text(interp: &mut Interp<'_>, text: &str, ext: bool) -> JsResult<Value> {
    parse_text_tracking(interp, text, ext, false)
}

/// [`parse_text`], optionally recording each primitive's source text.
///
/// The public `parse_text` never tracks: `std.parseExtJSON` has no reviver, so the source
/// table would always be dead weight.
fn parse_text_tracking(
    interp: &mut Interp<'_>,
    text: &str,
    ext: bool,
    track: bool,
) -> JsResult<Value> {
    let mut parser = Parser {
        bytes: text.as_bytes(),
        text,
        position: 0,
        ext,
        track,
        last_span: (0, 0),
    };
    parser.skip_whitespace();
    let value = match parser.value(interp) {
        Ok(value) => value,
        Err(error) => {
            return Err(crate::interp::Signal::Throw(json_error(
                interp, text, error,
            )));
        }
    };
    parser.skip_whitespace();
    if parser.position != parser.bytes.len() {
        return Err(crate::interp::Signal::Throw(json_error(
            interp,
            text,
            JsonError {
                message: "unexpected data after JSON value".to_string(),
                offset: parser.position,
            },
        )));
    }
    Ok(value)
}

fn parse(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToString(text)` — through `ToPrimitive`, so an object with a `toString` is parsed
    // from what that returns (and a symbol is a `TypeError`, not a `SyntaxError`).
    //
    // `Value::to_js_string` is the total convertor, and using it here made
    // `JSON.parse({toString: () => '"s"'})` a `SyntaxError`: the object's own spelling is
    // `[object Object]`, which no parser accepts.
    let text = interp.checked_to_string(&arg(args, 0))?;
    // The second argument rewrites the parsed tree bottom-up. Ignoring it made
    // `JSON.parse('{"a":1}', (k, v) => v * 2).a` answer `1`.
    let reviver = arg(args, 1);
    let is_reviver = matches!(&reviver, Value::Object(function) if function.is_callable());
    // Source text is only recorded when a reviver can observe it: `context.source` is the
    // one place the original spelling of a number survives (`1.0` parses to `1` but its
    // source is `"1.0"`), and without a reviver there is nobody to ask.
    let value = parse_text_tracking(interp, &text, false, is_reviver)?;
    if !is_reviver {
        return Ok(value);
    }
    // `InternalizeJSONProperty` starts from `{"": value}`, so the root is visited last and
    // may itself be replaced.
    let root = make_root_holder(interp, &value)?;
    let Value::Object(root) = &root else {
        return Ok(value);
    };
    // A primitive root has no container to carry its source, so it goes on the holder
    // under the empty key — which is the key the reviver sees for the root.
    if value.as_object().is_none() {
        let table = interp.new_object(None);
        table.define_data("", interp.string(text.trim()));
        interp.internal_set(root, "_json_source", Value::Object(table));
    }
    internalize_json_property(interp, root, "", &reviver)
}

/// `CreateDataProperty`, which differs from `Set` in exactly the case a reviver hits: an
/// existing non-configurable property keeps its value instead of being overwritten, and the
/// refusal is not an error.
fn create_data_property(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    key: &str,
    value: Value,
) -> JsResult<()> {
    let key = crate::object::PropertyKey::from(key);
    // A property that already exists and cannot be redefined keeps its old value: the
    // definition is refused rather than applied. `Object.defineProperty` would report that
    // refusal through its return value, but here a reviver that froze a property while
    // visiting an earlier key must simply see it stay frozen.
    if interp
        .object_get_own_property(object, &key)?
        .is_some_and(|existing| !existing.configurable)
    {
        return Ok(());
    }
    let property = crate::object::Property {
        value: Some(value),
        writable: true,
        enumerable: true,
        configurable: true,
        ..crate::object::Property::default()
    };
    interp.object_define_own_property(object, &key, property)?;
    Ok(())
}

/// `InternalizeJSONProperty`: call the reviver on every property, depth first, and drop the
/// ones it answers `undefined` for.
fn internalize_json_property(
    interp: &mut Interp<'_>,
    holder: &Gc<JsObject>,
    key: &str,
    reviver: &Value,
) -> JsResult<Value> {
    let Some(value) = interp.get_property(holder, key)? else {
        return Ok(Value::Undefined);
    };
    // Arrays are walked by index and objects by their enumerable own keys; a primitive has
    // nothing to walk, so it goes straight to the call.
    if let Value::Object(object) = &value {
        if object.is_array() {
            // §25.5.1.1 step 2.a.i: `LengthOfArrayLike(val)`, which is `Get(val, "length")`
            // followed by `ToLength` — both script-visible. Reading the internal slot
            // instead answered `0` for a **proxy** over an array (whose own slot is empty),
            // so the walk skipped an element entirely: `reviver-array-delete-err` plants a
            // proxy in the array and expects its `deleteProperty` trap to run. A `length`
            // getter or a `valueOf` in the length likewise has to run
            // (`reviver-array-length-get-err`, `reviver-array-length-coerce-err`).
            let length = match interp.get_property(object, "length")? {
                None | Some(Value::Undefined) => 0,
                Some(value) => {
                    let number = interp.to_js_number(&value)?;
                    if number.is_nan() || number <= 0.0 {
                        0
                    } else {
                        number.min(9_007_199_254_740_991.0) as usize
                    }
                }
            };
            for index in 0..length {
                let element_key = index.to_string();
                let replaced = internalize_json_property(interp, object, &element_key, reviver)?;
                if matches!(replaced, Value::Undefined) {
                    interp.delete_property(object, &element_key)?;
                } else {
                    // `CreateDataProperty`, not `Set`: when the property already exists and
                    // refuses redefinition the new value is dropped. A reviver that froze a
                    // property while visiting an earlier key must not have it overwritten by
                    // a later branch.
                    create_data_property(interp, object, &element_key, replaced)?;
                }
            }
        } else {
            for name in interp.object_own_property_keys(object)? {
                let Some(name) = name.as_str() else {
                    continue;
                };
                let name = name.to_string();
                let replaced = internalize_json_property(interp, object, &name, reviver)?;
                if matches!(replaced, Value::Undefined) {
                    interp.delete_property(object, &name)?;
                } else {
                    create_data_property(interp, object, &name, replaced)?;
                }
            }
        }
    }
    // `context`: a plain object, with `source` **only** when the value is a primitive
    // (§`InternalizeJSONProperty`). The property is created with
    // `CreateDataProperty`-attributes — writable, enumerable, configurable — which the
    // suite checks one by one.
    let context = interp.new_object(Some(interp.realm.object_proto.clone()));
    if value.as_object().is_none()
        && let Some(source) = json_source_of(interp, holder, key)
    {
        context.define("source", Property::with_attributes(source, true, true));
    }
    interp.call_value(
        reviver.clone(),
        Value::Object(holder.clone()),
        vec![interp.string(key), value, Value::Object(context)],
    )
}

/// The source text recorded for `holder[key]`, if any.
fn json_source_of(interp: &Interp<'_>, holder: &Gc<JsObject>, key: &str) -> Option<Value> {
    let table = interp.internal_get(holder, "_json_source")?;
    let table = table.as_object()?;
    table.own_property(key).and_then(|property| property.value)
}

/// A `SyntaxError` that reports where in the JSON text parsing failed.
///
/// The reference builds these with an explicit position, so the trace starts with
/// `    at <input>:line:column` — the position inside the text — and only then lists
/// the caller. `<input>` is the reference's placeholder for text that came from a
/// string rather than a file, so it is kept even when the caller is a real script.
fn json_error(interp: &mut Interp<'_>, text: &str, error: JsonError) -> Value {
    let (line, column) = line_and_column(text, error.offset);
    let trace = format!("    at <input>:{line}:{column}\n{}", interp.stack_trace());
    let value = interp.make_error("SyntaxError", &error.message);
    if let Value::Object(object) = &value {
        let text = interp.string(trace);
        object.define(
            "stack",
            crate::object::Property::with_attributes(text, true, true),
        );
    }
    value
}

/// The 1-based line and column of `offset` in `text`.
///
/// Columns count UTF-16 code units, like every other position in this engine, so a
/// character outside the BMP counts twice.
fn line_and_column(text: &str, offset: usize) -> (usize, usize) {
    let before = &text[..offset.min(text.len())];
    let line = before.matches('\n').count() + 1;
    let line_start = before.rfind('\n').map_or(0, |index| index + 1);
    let column = before[line_start..].encode_utf16().count() + 1;
    (line, column)
}

/// A JSON syntax error and where in the JSON text it happened.
///
/// The offset is what lets `JSON.parse` report a position the way the reference does:
/// its stack starts with the line and column inside the *text being parsed*, not with
/// the caller's frame.
struct JsonError {
    message: String,
    offset: usize,
}

struct Parser<'a> {
    bytes: &'a [u8],
    text: &'a str,
    position: usize,
    /// Whether the extended dialect is in force. Every relaxation below is gated on it, so
    /// `JSON.parse` keeps rejecting what RFC 8259 rejects.
    ext: bool,
    /// Whether to record the source text of primitive values.
    ///
    /// Only needed when a reviver is present, because `reviver(key, value, {source})` is the
    /// one place the text is observable. Recording is on the *parser* rather than a second
    /// pass so the slice is exact: a re-parse would have to guess, and `1.0` versus `1`
    /// would be a coin flip.
    track: bool,
    /// The byte span of the value [`Parser::value`] returned most recently.
    last_span: (usize, usize),
}

/// Whether `text` matches RFC 8259's `number` production exactly.
///
/// (RFC 8259 §6: `int` is `0` or a nonzero digit followed by digits, `frac` needs a digit
/// after the point, and `exp` needs one after the `e`.)
fn is_rfc_number(text: &str) -> bool {
    let bytes = text.as_bytes();
    let mut index = 0;
    if bytes.first() == Some(&b'-') {
        index += 1;
    }
    // `int`: a lone `0`, or a nonzero digit and then any digits.
    match bytes.get(index) {
        Some(b'0') => index += 1,
        Some(b'1'..=b'9') => {
            index += 1;
            while bytes.get(index).is_some_and(u8::is_ascii_digit) {
                index += 1;
            }
        }
        _ => return false,
    }
    // `frac`: the point needs at least one digit after it.
    if bytes.get(index) == Some(&b'.') {
        index += 1;
        let digits = index;
        while bytes.get(index).is_some_and(u8::is_ascii_digit) {
            index += 1;
        }
        if index == digits {
            return false;
        }
    }
    // `exp`: likewise.
    if matches!(bytes.get(index), Some(b'e' | b'E')) {
        index += 1;
        if matches!(bytes.get(index), Some(b'+' | b'-')) {
            index += 1;
        }
        let digits = index;
        while bytes.get(index).is_some_and(u8::is_ascii_digit) {
            index += 1;
        }
        if index == digits {
            return false;
        }
    }
    index == bytes.len()
}

/// Whether `byte` may start a bare identifier key: the reference's `TOK_IDENT` start set.
fn is_identifier_start(byte: u8) -> bool {
    byte.is_ascii_alphabetic() || byte == b'_' || byte == b'$'
}

impl Parser<'_> {
    /// An error blamed on the parser's current position.
    fn error<T>(&self, message: impl Into<String>) -> Result<T, JsonError> {
        Err(JsonError {
            message: message.into(),
            offset: self.position,
        })
    }

    fn skip_whitespace(&mut self) {
        loop {
            while let Some(byte) = self.bytes.get(self.position) {
                match byte {
                    b' ' | b'\t' | b'\n' | b'\r' => self.position += 1,
                    // `JSONWhitespace` does not match <VT> or <FF>; the extended dialect
                    // does, so `formfeed` and `vertical tab` count as space there.
                    b'\x0b' | b'\x0c' if self.ext => self.position += 1,
                    _ => break,
                }
            }
            // Comments are whitespace in the extended dialect, and they may abut each other,
            // so this is a loop rather than one check.
            if !self.ext || !self.skip_one_comment() {
                return;
            }
        }
    }

    /// Skip one `/* … */` or `// …` comment, reporting whether there was one.
    ///
    /// An unterminated block comment leaves the position at the end, so the caller reports
    /// "unexpected end of JSON input" instead of silently accepting a truncated document.
    fn skip_one_comment(&mut self) -> bool {
        if self.bytes.get(self.position) != Some(&b'/') {
            return false;
        }
        match self.bytes.get(self.position + 1) {
            Some(b'*') => {
                self.position += 2;
                while self.position < self.bytes.len() {
                    if self.bytes[self.position..].starts_with(b"*/") {
                        self.position += 2;
                        return true;
                    }
                    self.position += 1;
                }
                true
            }
            Some(b'/') => {
                self.position += 2;
                // A line comment ends at CR, LF, or a Unicode line separator.
                while let Some(character) = self.text[self.position..].chars().next() {
                    if matches!(character, '\r' | '\n' | '\u{2028}' | '\u{2029}') {
                        break;
                    }
                    self.position += character.len_utf8();
                }
                true
            }
            _ => false,
        }
    }

    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.position).copied()
    }

    fn value(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
        self.skip_whitespace();
        let start = self.position;
        let value = self.value_inner(interp)?;
        self.last_span = (start, self.position);
        Ok(value)
    }

    /// The source text of the value at `span`, when tracking is on.
    fn source_of(&self, span: (usize, usize)) -> Option<String> {
        if !self.track {
            return None;
        }
        self.text.get(span.0..span.1).map(str::to_string)
    }

    fn value_inner(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
        match self.peek() {
            None => self.error("unexpected end of JSON input"),
            Some(b'{') => self.object(interp),
            Some(b'[') => self.array(interp),
            Some(b'"') => Ok(interp.string(self.string()?)),
            // A single-quoted string is only a value in the extended dialect.
            Some(b'\'') if self.ext => Ok(interp.string(self.string()?)),
            Some(b't') => self.literal("true", Value::Bool(true)),
            Some(b'f') => self.literal("false", Value::Bool(false)),
            Some(b'n') => self.literal("null", Value::Null),
            // The extended dialect starts a number at `.` (as in `.1`) and at `+`.
            Some(b'.') if self.ext => self.number(),
            Some(b'+') if self.ext => self.number(),
            Some(_) => self.number(),
        }
    }

    fn literal(&mut self, word: &str, value: Value) -> Result<Value, JsonError> {
        if self.text[self.position..].starts_with(word) {
            self.position += word.len();
            Ok(value)
        } else {
            self.error("unexpected token")
        }
    }

    fn number(&mut self) -> Result<Value, JsonError> {
        // RFC 8259 has a number start with `-` or a digit, and the scan below is happy to
        // take a leading `+` or `.` — which `f64::from_str` then accepts. Without this
        // guard `JSON.parse("+1")` and `JSON.parse(".1")` succeeded, which they must not.
        // The extended dialect allows both, so those two are gated on `ext`.
        // The extended dialect is checked by its own parser below: `Infinity` and `NaN`
        // start with letters, and `+` and `.` are legal there, so a first-character rule
        // would reject exactly the values it is meant to add.
        if !self.ext {
            match self.peek() {
                Some(b'-') | Some(b'0'..=b'9') => {}
                _ => return self.error("unexpected token in number"),
            }
        }
        let start = self.position;
        if matches!(self.peek(), Some(b'-')) || (self.ext && matches!(self.peek(), Some(b'+'))) {
            self.position += 1;
        }
        if self.ext {
            let negative = self.bytes.get(start) == Some(&b'-');
            // `Infinity` and `NaN` are only reachable after the sign has been consumed, so
            // `-Infinity` and `+NaN` fall out for free — same order as the reference.
            if self.rest().starts_with("Infinity") {
                self.position += "Infinity".len();
                return Ok(Value::Float(if negative {
                    f64::NEG_INFINITY
                } else {
                    f64::INFINITY
                }));
            }
            if self.rest().starts_with("NaN") {
                self.position += "NaN".len();
                // The sign does not survive: `-NaN` is still `NaN`, which is why the
                // reference's own test only checks `isNaN` for the signed forms.
                return Ok(Value::Float(f64::NAN));
            }
            // Radix prefixes. The reference accepts all three, though its comment only
            // mentions hexadecimal and octal.
            if self.bytes.get(self.position) == Some(&b'0') {
                let radix = match self.bytes.get(self.position + 1) {
                    Some(b'x' | b'X') => Some(16u32),
                    Some(b'o' | b'O') => Some(8),
                    Some(b'b' | b'B') => Some(2),
                    _ => None,
                };
                if let Some(radix) = radix {
                    self.position += 2;
                    let digits = self.position;
                    while self
                        .peek()
                        .is_some_and(|byte| (byte as char).is_digit(radix))
                    {
                        self.position += 1;
                    }
                    if self.position == digits {
                        return self.error("unexpected token in number");
                    }
                    let magnitude = u64::from_str_radix(&self.text[digits..self.position], radix)
                        .map(|value| value as f64)
                        .unwrap_or(f64::NAN);
                    return Ok(Value::Float(if negative { -magnitude } else { magnitude }));
                }
            }
        }
        while let Some(byte) = self.peek() {
            match byte {
                b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-' => self.position += 1,
                _ => break,
            }
        }
        let text = &self.text[start..self.position];
        // The scan above is a *character-class* run, and `f64::from_str` is more permissive
        // than RFC 8259: it takes `01`, `1.` and `-01`, all of which the grammar rejects
        // (`int` is `0` or a nonzero digit followed by digits; `frac` needs a digit after the
        // point). Left unguarded, `JSON.parse("01")` answered `1` where the reference throws.
        //
        // Only in the strict dialect: the extended one is deliberately loose, and its own
        // callers (`std.parseExtJSON`) want `+1` and `.5`.
        if !self.ext && !is_rfc_number(text) {
            return self.error("invalid number");
        }
        text.parse::<f64>()
            .map(Value::Float)
            .map_err(|_| JsonError {
                message: "invalid number".to_string(),
                offset: start,
            })
    }

    /// The text from the current position to the end.
    fn rest(&self) -> &str {
        &self.text[self.position.min(self.text.len())..]
    }

    fn string(&mut self) -> Result<String, JsonError> {
        // The opening quote is already known to be there. `'` only reaches here in the
        // extended dialect; the callers check.
        let separator = self.peek().unwrap_or(b'"');
        self.position += 1;
        let mut out = String::new();
        loop {
            let Some(byte) = self.peek() else {
                return self.error("unterminated string");
            };
            match byte {
                _ if byte == separator => {
                    self.position += 1;
                    return Ok(out);
                }
                // A raw control character is not allowed in a JSON string: it has to be
                // escaped. Accepting one made `JSON.parse('"a<TAB>b"')` succeed where the
                // grammar requires a `SyntaxError`.
                0x00..=0x1F => {
                    return self.error("control character in string");
                }
                b'\\' => {
                    self.position += 1;
                    let Some(escape) = self.peek() else {
                        return self.error("unterminated escape");
                    };
                    self.position += 1;
                    let start_of_escape = self.position - 1;
                    match escape {
                        // An escaped delimiter, and only the delimiter: `\"` inside a
                        // single-quoted string is a bad escape in the reference too.
                        b'"' if separator == b'"' => out.push('"'),
                        b'\'' if separator == b'\'' => out.push('\''),
                        b'\\' => out.push('\\'),
                        b'/' => out.push('/'),
                        b'b' => out.push('\u{8}'),
                        b'f' => out.push('\u{c}'),
                        b'n' => out.push('\n'),
                        b'r' => out.push('\r'),
                        b't' => out.push('\t'),
                        // `\v` is not a JSON escape; the extended dialect adds it.
                        b'v' if self.ext => out.push('\u{b}'),
                        // A backslash before a newline continues the string on the next
                        // line, dropping both characters. Only `\n`: `\r\n` is not
                        // handled, matching `json_parse_string`.
                        b'\n' if self.ext => {}
                        b'u' => {
                            let end = self.position + 4;
                            if end > self.bytes.len() {
                                return self.error("truncated \\u escape");
                            }
                            let hex = &self.text[self.position..end];
                            let unit = u16::from_str_radix(hex, 16).map_err(|_| JsonError {
                                message: "invalid \\u escape".to_string(),
                                offset: start_of_escape,
                            })?;
                            self.position = end;
                            // A surrogate pair arrives as two escapes; reassemble it.
                            if (0xd800..0xdc00).contains(&unit)
                                && self.text[self.position..].starts_with("\\u")
                            {
                                let tail_end = self.position + 6;
                                if tail_end <= self.bytes.len() {
                                    let low = u16::from_str_radix(
                                        &self.text[self.position + 2..tail_end],
                                        16,
                                    )
                                    .unwrap_or(0);
                                    if (0xdc00..0xe000).contains(&low) {
                                        let combined = 0x10000
                                            + ((unit as u32 - 0xd800) << 10)
                                            + (low as u32 - 0xdc00);
                                        out.push(char::from_u32(combined).unwrap_or('\u{fffd}'));
                                        self.position = tail_end;
                                        continue;
                                    }
                                }
                            }
                            out.push(char::from_u32(unit as u32).unwrap_or('\u{fffd}'));
                        }
                        // The offending character is the one just consumed, so the
                        // position has to step back over it.
                        other => {
                            return Err(JsonError {
                                message: format!("invalid escape \\{}", other as char),
                                offset: self.position - 1,
                            });
                        }
                    }
                }
                _ => {
                    // Copy one whole UTF-8 character so multi-byte text survives.
                    let rest = &self.text[self.position..];
                    let character = rest.chars().next().ok_or_else(|| JsonError {
                        message: "invalid UTF-8".to_string(),
                        offset: self.position,
                    })?;
                    out.push(character);
                    self.position += character.len_utf8();
                }
            }
        }
    }

    /// A bare identifier used as a property key.
    ///
    /// The reference runs this through the full JS identifier tables, so it accepts non-ASCII
    /// letters. `is_alphanumeric` covers the same ground without pulling those tables into
    /// the JSON parser; an identifier the two disagree about would have to start with a
    /// non-ASCII, non-letter character, which no realistic config file does.
    fn identifier(&mut self) -> Result<String, JsonError> {
        let start = self.position;
        while self
            .text
            .get(start..)
            .and_then(|rest| rest.chars().next())
            .is_some_and(|_| self.position < self.text.len())
        {
            let character = self.text[self.position..]
                .chars()
                .next()
                .expect("the loop condition checked");
            let keep = if self.position == start {
                is_identifier_start(character as u32 as u8)
                    || character.is_alphabetic()
                    || character == '_'
                    || character == '$'
            } else {
                character.is_alphanumeric() || character == '_' || character == '$'
            };
            if !keep {
                break;
            }
            self.position += character.len_utf8();
        }
        if self.position == start {
            return self.error("expected an identifier");
        }
        Ok(self.text[start..self.position].to_string())
    }

    fn array(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
        self.position += 1;
        let mut elements = Vec::new();
        // `key -> source` for the primitive children only. An array or object child gets no
        // `source` at all, per `CreateJSONParseRecord`'s "if value is not an Object".
        let mut sources: Vec<String> = Vec::new();
        self.skip_whitespace();
        if matches!(self.peek(), Some(b']')) {
            self.position += 1;
            return Ok(Value::Object(interp.new_array(elements)));
        }
        loop {
            let value = self.value(interp)?;
            let source = if value.as_object().is_none() {
                self.source_of(self.last_span)
            } else {
                None
            };
            sources.push(source.unwrap_or_default());
            elements.push(value);
            self.skip_whitespace();
            match self.peek() {
                Some(b',') => {
                    self.position += 1;
                    // A trailing comma closes the array in the extended dialect.
                    self.skip_whitespace();
                    if self.ext && matches!(self.peek(), Some(b']')) {
                        self.position += 1;
                        return Ok(self.finish_array(interp, elements, sources));
                    }
                }
                Some(b']') => {
                    self.position += 1;
                    return Ok(self.finish_array(interp, elements, sources));
                }
                _ => return self.error("expected ',' or ']'"),
            }
        }
    }

    /// Attach the `key -> source` table to a parsed array, under a hidden slot.
    ///
    /// A slot rather than a visible property: `Object.keys`/`JSON.stringify`/`for...in` must
    /// not see it, and `assertOnlyOwnProperties` in the test suite checks exactly that the
    /// parsed objects have no extra own properties.
    fn finish_array(
        &self,
        interp: &mut Interp<'_>,
        elements: Vec<Value>,
        sources: Vec<String>,
    ) -> Value {
        let array = interp.new_array(elements);
        if sources.iter().any(|source| !source.is_empty()) {
            let table = interp.new_object(None);
            for (index, source) in sources.into_iter().enumerate() {
                if !source.is_empty() {
                    table.define_data(&index.to_string(), interp.string(source));
                }
            }
            interp.internal_set(&array, "_json_source", Value::Object(table));
        }
        Value::Object(array)
    }

    /// [`Parser::finish_array`] for objects, whose keys may be arbitrary strings.
    fn attach_sources(
        &self,
        interp: &mut Interp<'_>,
        object: &Gc<JsObject>,
        sources: Vec<(String, String)>,
    ) {
        if sources.is_empty() {
            return;
        }
        let table = interp.new_object(None);
        for (key, source) in sources {
            table.define_data(&key, interp.string(source));
        }
        interp.internal_set(object, "_json_source", Value::Object(table));
    }

    fn object(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
        self.position += 1;
        let proto = interp.realm.object_proto.clone();
        let object = interp.new_object(Some(proto));
        let mut sources: Vec<(String, String)> = Vec::new();
        self.skip_whitespace();
        if matches!(self.peek(), Some(b'}')) {
            self.position += 1;
            return Ok(Value::Object(object));
        }
        loop {
            self.skip_whitespace();
            let key = match self.peek() {
                Some(b'"') => self.string()?,
                // A bare identifier as a key, e.g. `{ z2: null }`.
                Some(b'\'') if self.ext => self.string()?,
                Some(byte) if self.ext && is_identifier_start(byte) => self.identifier()?,
                _ => return self.error("expecting property name"),
            };
            self.skip_whitespace();
            if !matches!(self.peek(), Some(b':')) {
                return self.error("expected ':'");
            }
            self.position += 1;
            let value = self.value(interp)?;
            if value.as_object().is_none()
                && let Some(source) = self.source_of(self.last_span)
            {
                sources.push((key.clone(), source));
            }
            object.define_data(&key, value);
            self.skip_whitespace();
            match self.peek() {
                Some(b',') => {
                    self.position += 1;
                    // A trailing comma closes the object in the extended dialect.
                    self.skip_whitespace();
                    if self.ext && matches!(self.peek(), Some(b'}')) {
                        self.position += 1;
                        self.attach_sources(interp, &object, sources);
                        return Ok(Value::Object(object));
                    }
                }
                Some(b'}') => {
                    self.position += 1;
                    self.attach_sources(interp, &object, sources);
                    return Ok(Value::Object(object));
                }
                _ => return self.error("expected ',' or '}'"),
            }
        }
    }
}