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
use super::*;
impl<'a> Interp<'a> {
/// `InternalizeJSONProperty` — the `JSON.parse` reviver walk *with source-text
/// access* (the `json-parse-with-source` proposal). Reads `val = Get(holder,
/// name)` via `[[Get]]`; if `val` is an array its indices are recursed, else
/// its snapshot of own enumerable keys, bottom-up. It additionally passes the
/// reviver a third `context` argument: a plain
/// object that, for a value that is a primitive **still equal to the one the
/// parser produced at this position**, carries a `source` data property with
/// that value's exact JSON source text. Structural values (objects/arrays) and
/// values a reviver has forward-substituted get a bare `{}` context.
///
/// `snapshot` is the parse-time source node for the value currently at
/// `holder[key]` (or `None` for a member the reviver added).
pub(crate) fn json_revive_ctx(
&mut self,
holder: crate::heap::Handle,
key: &str,
reviver: NanBox,
snapshot: Option<&JsonSrc>,
) -> Result<NanBox, ExecError> {
let value = self.read_member(holder, key)?;
if let Some(vh) = value.as_handle().map(Handle::from_raw) {
if self.realm.is_array(self.proxy_key_target(vh)) {
let len_v = self.read_member(vh, "length")?;
let len_f = self.coerce_to_integer_or_infinity(len_v)?;
let len = len_f.clamp(0.0, 9_007_199_254_740_991.0) as usize;
for i in 0..len {
let ks = alloc::format!("{i}");
let child = match snapshot {
Some(JsonSrc::Array(v)) => v.get(i),
_ => None,
};
let nv = self.json_revive_ctx(vh, &ks, reviver, child)?;
if matches!(nv.unpack(), Unpacked::Undefined) {
self.delete_property_of(vh, &ks)?;
} else {
let desc = self.realm.new_object();
self.realm.set_property(desc, "value", nv);
self.realm
.set_property(desc, "writable", NanBox::boolean(true));
self.realm
.set_property(desc, "enumerable", NanBox::boolean(true));
self.realm
.set_property(desc, "configurable", NanBox::boolean(true));
self.apply_descriptor(vh, &ks, desc, true)?;
}
}
} else if self.realm.object_keys(vh).is_some() || self.realm.proxy_at(vh).is_some() {
let keys = if let Some(pk) = self.proxy_own_enumerable_keys(vh)? {
pk
} else {
self.realm
.object_keys(self.proxy_key_target(vh))
.unwrap_or_default()
};
for k in keys {
let child = match snapshot {
Some(JsonSrc::Object(pairs)) => {
pairs.iter().find(|(pk, _)| pk == &k).map(|(_, s)| s)
}
_ => None,
};
let nv = self.json_revive_ctx(vh, &k, reviver, child)?;
if matches!(nv.unpack(), Unpacked::Undefined) {
self.delete_property_of(vh, &k)?;
} else {
let desc = self.realm.new_object();
self.realm.set_property(desc, "value", nv);
self.realm
.set_property(desc, "writable", NanBox::boolean(true));
self.realm
.set_property(desc, "enumerable", NanBox::boolean(true));
self.realm
.set_property(desc, "configurable", NanBox::boolean(true));
self.apply_descriptor(vh, &k, desc, true)?;
}
}
}
}
// Build the `context` object. Only a primitive value that is *still* the
// one the parser produced here (SameValue) exposes its `source`.
let context = self.realm.new_object();
if !self.is_object_value(value)
&& let Some(JsonSrc::Prim { value: pv, source }) = snapshot
&& self.realm.same_value(*pv, value)
{
let src_box = self.new_str(source);
self.realm.set_property(context, "source", src_box);
}
let kb = self.new_str(key);
self.call_with_this(
reviver,
NanBox::handle(holder.to_raw()),
&[kb, value, NanBox::handle(context.to_raw())],
)
}
/// `JSON.stringify(value, replacer, space)` — the unified spec algorithm
/// (25.5.2): a single recursive `SerializeJSONProperty` that applies the
/// replacer (function or property-list array) and `toJSON` at each node,
/// detects cycles, and honors the `space` gap. Returns `None` when the top
/// value serializes to nothing (`undefined`/function/symbol).
pub(crate) fn json_stringify(
&mut self,
value: NanBox,
replacer: NanBox,
space: NanBox,
) -> Result<Option<String>, ExecError> {
// ReplacerFunction / PropertyList from `replacer`.
let mut replacer_fn = NanBox::undefined();
let mut property_list: Option<Vec<String>> = None;
if let Some(rh) = replacer.as_handle().map(Handle::from_raw) {
if self.is_callable(rh) {
replacer_fn = replacer;
} else if self.realm.is_array(self.proxy_key_target(rh)) {
// Build the PropertyList via `[[Get]]` (length + each index) so a
// Proxy replacer drives its traps and an element getter's abrupt
// completion propagates. ToString each element that is a String, a
// Number, or a String/Number wrapper; dedupe, preserve order.
let len_v = self.read_member(rh, "length")?;
let len = self
.coerce_to_integer_or_infinity(len_v)?
.clamp(0.0, 9_007_199_254_740_991.0) as usize;
let mut list: Vec<String> = Vec::new();
for i in 0..len {
let e = self.read_member(rh, &alloc::format!("{i}"))?;
let item = match e.unpack() {
Unpacked::Number(_) => Some(self.realm.to_display_string(e)),
Unpacked::Handle(raw) => {
let h = Handle::from_raw(raw);
if self.realm.is_string_handle(h) {
Some(self.realm.to_display_string(e))
} else if let Some(prim) = self.realm.get_property(h, PRIM_WRAP) {
// A String/Number wrapper contributes its key via
// ToString/ToNumber (honoring a user valueOf/toString).
// A Number *or* String wrapper's key is `ToString(v)`
// (per PropertyList construction) — not ToNumber.
match prim.unpack() {
Unpacked::Number(_) => Some(self.coerce_to_string(e)?),
Unpacked::Handle(pr)
if self
.realm
.string_value(Handle::from_raw(pr))
.is_some() =>
{
Some(self.coerce_to_string(e)?)
}
_ => None,
}
} else {
None
}
}
_ => None,
};
if let Some(k) = item
&& !list.contains(&k)
{
list.push(k);
}
}
property_list = Some(list);
}
}
// The `space` gap: a Number (or Number wrapper) → that many spaces (clamped
// to 0..=10); a String (or String wrapper) → its first 10 code units; else
// empty (compact).
let space = self.json_unwrap_wrapper(space)?;
let gap = if let Some(n) = space.as_number() {
// ToIntegerOrInfinity then `min(10)` spaces; a non-positive count is 0.
// The cast to `usize` truncates toward zero (ToInteger) and a NaN maps
// to 0, matching `min(MIN(ToInteger(space), 10), 0)`-style clamping.
let n = if n >= 1.0 { (n as usize).min(10) } else { 0 };
" ".repeat(n)
} else if let Some(s) = space
.as_handle()
.and_then(|r| self.realm.string_value(Handle::from_raw(r)))
{
s.chars().take(10).collect()
} else {
String::new()
};
// The wrapper holder `{ "": value }`.
let holder = self.realm.new_object();
self.realm.set_property(holder, "", value);
let mut stack: Vec<Handle> = Vec::new();
self.serialize_json_property(
holder,
"",
&replacer_fn,
property_list.as_deref(),
&gap,
"",
&mut stack,
)
}
/// The `space` argument's ToPrimitive: a `[[NumberData]]` wrapper becomes
/// `ToNumber(space)` and a `[[StringData]]` wrapper `ToString(space)` (both
/// honoring a user `valueOf`/`toString`); anything else is returned unchanged.
fn json_unwrap_wrapper(&mut self, v: NanBox) -> Result<NanBox, ExecError> {
if let Some(h) = v.as_handle().map(Handle::from_raw)
&& let Some(prim) = self.realm.get_property(h, PRIM_WRAP)
{
return Ok(match prim.unpack() {
Unpacked::Number(_) => self.coerce_to_number(v)?,
Unpacked::Handle(r) if self.realm.string_value(Handle::from_raw(r)).is_some() => {
let s = self.coerce_to_string(v)?;
self.new_str(&s)
}
_ => prim,
});
}
Ok(v)
}
/// `SerializeJSONProperty(key, holder)` — serializes `holder[key]`, applying
/// `toJSON`, then the replacer function; returns `None` if the value drops
/// (`undefined`/callable/symbol at a non-array position).
#[allow(clippy::too_many_arguments)]
fn serialize_json_property(
&mut self,
holder: Handle,
key: &str,
replacer_fn: &NanBox,
property_list: Option<&[String]>,
gap: &str,
indent: &str,
stack: &mut Vec<Handle>,
) -> Result<Option<String>, ExecError> {
// value = Get(holder, key) — through read_member so getters fire.
let mut value = self.read_member(holder, key)?;
// If value is an Object (or BigInt) with a callable `toJSON`, call it.
if let Some(h) = value.as_handle().map(Handle::from_raw) {
let tj = self.read_member(h, "toJSON")?;
if self.is_callable_value(tj) {
let kb = self.new_str(key);
value = self.call_with_this(tj, value, &[kb])?;
}
}
// ReplacerFunction: value = replacer.call(holder, key, value).
if self.is_callable_value(*replacer_fn) {
let kb = self.new_str(key);
value =
self.call_with_this(*replacer_fn, NanBox::handle(holder.to_raw()), &[kb, value])?;
}
self.serialize_json_value(value, replacer_fn, property_list, gap, indent, stack)
}
/// The type-dispatch tail of SerializeJSONProperty: serialize an already-
/// (toJSON/replacer-)transformed `value`.
#[allow(clippy::too_many_arguments)]
fn serialize_json_value(
&mut self,
value: NanBox,
replacer_fn: &NanBox,
property_list: Option<&[String]>,
gap: &str,
indent: &str,
stack: &mut Vec<Handle>,
) -> Result<Option<String>, ExecError> {
// Unwrap a primitive-wrapper object to its boxed primitive first (so a
// `new Number(1)` serializes as `1`, `new String("x")` as `"x"`).
let value = if let Some(h) = value.as_handle().map(Handle::from_raw) {
// RawJSON object: emit the stored source verbatim.
if self.realm.get_property(h, RAW_JSON_BRAND).is_some()
&& let Some(raw) = self.realm.get_property(h, "rawJSON")
{
return Ok(Some(self.realm.to_display_string(raw)));
}
if let Some(prim) = self.realm.get_property(h, PRIM_WRAP) {
// SerializeJSONProperty step 4: a `[[NumberData]]` wrapper is
// `ToNumber(value)` and a `[[StringData]]` wrapper is
// `ToString(value)` — both applied to the *wrapper*, so a custom
// `valueOf`/`toString` is honored. Boolean/BigInt wrappers use the
// boxed primitive directly.
match prim.unpack() {
Unpacked::Number(_) => self.coerce_to_number(value)?,
Unpacked::Handle(r)
if self.realm.string_value(Handle::from_raw(r)).is_some() =>
{
let s = self.coerce_to_string(value)?;
self.new_str(&s)
}
_ => prim,
}
} else {
value
}
} else {
value
};
match value.unpack() {
Unpacked::Null => Ok(Some(String::from("null"))),
Unpacked::Bool(b) => Ok(Some(String::from(if b { "true" } else { "false" }))),
Unpacked::Number(n) => Ok(Some(if n.is_finite() {
self.realm.to_display_string(value)
} else {
String::from("null")
})),
Unpacked::Undefined => Ok(None),
Unpacked::Handle(raw) => {
let h = Handle::from_raw(raw);
if let Some(bytes) = self.realm.string_bytes(h) {
return Ok(Some(json_quote_wtf8(&bytes)));
}
if self.realm.bigint_at(h).is_some() {
let m = self.new_str("Do not know how to serialize a BigInt");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A Symbol value serializes to nothing (`typeof` is "symbol"), both
// as a value and (via the object key set) as a key.
if self.realm.symbol_at(h).is_some() {
return Ok(None);
}
// A callable value (function or class constructor) serializes to
// nothing (`typeof` is "function").
if self.is_callable(h) || self.realm.class_at(h).is_some() {
return Ok(None);
}
// Array vs object, via `IsArray` (which unwraps a proxy chain to
// its target — a proxy over an array serializes as an array). A
// typed array is NOT an Array exotic, so it serializes as an
// object keyed by its indices (`{"0":1,…}`), per `JSON.stringify`.
if self.is_array_unwrap_proxy(value)? {
self.serialize_json_array(h, replacer_fn, property_list, gap, indent, stack)
.map(Some)
} else {
self.serialize_json_object(h, replacer_fn, property_list, gap, indent, stack)
.map(Some)
}
}
}
}
/// `SerializeJSONObject` — `{ … }` with the PropertyList (or own enumerable
/// keys), recursing per member; cycle-checked via `stack`.
#[allow(clippy::too_many_arguments)]
fn serialize_json_object(
&mut self,
h: Handle,
replacer_fn: &NanBox,
property_list: Option<&[String]>,
gap: &str,
indent: &str,
stack: &mut Vec<Handle>,
) -> Result<String, ExecError> {
if stack.contains(&h) {
let m = self.new_str("Converting circular structure to JSON");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
stack.push(h);
let new_indent = alloc::format!("{indent}{gap}");
// The key set: the explicit PropertyList, else the object's own enumerable
// string keys (a typed array enumerates its integer indices).
let keys: Vec<String> = match property_list {
Some(list) => list.to_vec(),
None => {
if let Some(len) = self.realm.typed_len(h) {
(0..len).map(|i| alloc::format!("{i}")).collect()
} else if self.realm.proxy_at(h).is_some() {
// A proxy drives `[[OwnPropertyKeys]]` (the `ownKeys` trap, or
// trapless forwarding to the target) then filters to own
// enumerable **string** keys via `[[GetOwnProperty]]` (symbols
// never appear in JSON). Values are read later through the
// proxy's `get` trap by `serialize_json_property`.
let mut ks = Vec::new();
for key in self.own_property_keys_values(h)? {
let name = self.member_key(key);
if name.starts_with('\u{0}') {
continue; // a symbol key (internal `\0sym:` form)
}
let desc = self.descriptor_of(h, &name)?;
if matches!(desc.unpack(), Unpacked::Undefined) {
continue;
}
let enumerable = desc
.as_handle()
.map(Handle::from_raw)
.and_then(|dh| self.realm.get_property(dh, "enumerable"))
.is_some_and(|v| self.realm.truthy(v));
if enumerable {
ks.push(name);
}
}
ks
} else {
self.realm.object_keys(h).unwrap_or_default()
}
}
};
let mut parts: Vec<String> = Vec::new();
for k in keys {
if let Some(s) = self.serialize_json_property(
h,
&k,
replacer_fn,
property_list,
gap,
&new_indent,
stack,
)? {
let sep = if gap.is_empty() { ":" } else { ": " };
parts.push(alloc::format!("{}{sep}{s}", json_quote(&k)));
}
}
stack.pop();
let out = if parts.is_empty() {
String::from("{}")
} else if gap.is_empty() {
alloc::format!("{{{}}}", parts.join(","))
} else {
alloc::format!(
"{{\n{new_indent}{}\n{indent}}}",
parts.join(&alloc::format!(",\n{new_indent}"))
)
};
Ok(out)
}
/// `SerializeJSONArray` — `[ … ]`, each element serialized (a dropped element
/// becomes `null`); cycle-checked via `stack`.
#[allow(clippy::too_many_arguments)]
fn serialize_json_array(
&mut self,
h: Handle,
replacer_fn: &NanBox,
property_list: Option<&[String]>,
gap: &str,
indent: &str,
stack: &mut Vec<Handle>,
) -> Result<String, ExecError> {
if stack.contains(&h) {
let m = self.new_str("Converting circular structure to JSON");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
stack.push(h);
let new_indent = alloc::format!("{indent}{gap}");
let len = if self.realm.typed_kind(h).is_some() {
self.realm.typed_len(h).unwrap_or(0)
} else if self.realm.proxy_at(h).is_some() {
// A proxy over an array: `LengthOfArrayLike` = ToLength(Get(h,"length")),
// read through the proxy's `get` trap.
let lv = self.read_member(h, "length")?;
let ln = self.coerce_to_number(lv)?;
let n = self.realm.to_number(ln);
if n.is_finite() && n > 0.0 {
(n as usize).min(self.realm.limits.max_array_len)
} else {
0
}
} else {
self.realm.array_length(h).unwrap_or(0)
};
let mut parts: Vec<String> = Vec::with_capacity(len);
for i in 0..len {
let ks = alloc::format!("{i}");
// A PropertyList does NOT filter array indices (arrays ignore it for
// their own elements), but it MUST propagate to any nested objects, so
// pass it through to the recursive serialization.
let s = self
.serialize_json_property(
h,
&ks,
replacer_fn,
property_list,
gap,
&new_indent,
stack,
)?
.unwrap_or_else(|| String::from("null"));
parts.push(s);
}
stack.pop();
let out = if parts.is_empty() {
String::from("[]")
} else if gap.is_empty() {
alloc::format!("[{}]", parts.join(","))
} else {
alloc::format!(
"[\n{new_indent}{}\n{indent}]",
parts.join(&alloc::format!(",\n{new_indent}"))
)
};
Ok(out)
}
/// A `SyntaxError` for a malformed `JSON.parse` input (the spec error type, so
/// `catch (e) { e instanceof SyntaxError }` works).
pub(crate) fn json_error(&mut self, msg: &str) -> ExecError {
let m = self.new_str(msg);
ExecError::Throw(self.make_error(N_ERROR_BASE + 3, Some(m)))
}
pub(crate) fn json_parse(
&mut self,
c: &[char],
pos: &mut usize,
depth: usize,
) -> Result<NanBox, ExecError> {
skip_ws(c, pos);
let err = |s: &mut Self| s.json_error("Unexpected end of JSON input");
let Some(&ch) = c.get(*pos) else {
return Err(err(self));
};
if matches!(ch, '[' | '{') && depth >= self.realm.limits.max_json_depth {
return Err(self.json_error("Maximum JSON nesting depth exceeded"));
}
match ch {
'n' => self.json_lit(c, pos, "null", NanBox::null()),
't' => self.json_lit(c, pos, "true", NanBox::boolean(true)),
'f' => self.json_lit(c, pos, "false", NanBox::boolean(false)),
'"' => {
let s = self.json_string(c, pos)?;
Ok(self.new_str_bytes(s))
}
'[' => {
*pos += 1;
let mut elems = Vec::new();
skip_ws(c, pos);
if c.get(*pos) == Some(&']') {
*pos += 1;
return Ok(NanBox::handle(self.realm.new_array(elems).to_raw()));
}
loop {
let v = self.json_parse(c, pos, depth + 1)?;
elems.push(v);
skip_ws(c, pos);
match c.get(*pos) {
Some(',') => *pos += 1,
Some(']') => {
*pos += 1;
break;
}
_ => return Err(self.json_error("Expected ',' or ']'")),
}
}
Ok(NanBox::handle(self.realm.new_array(elems).to_raw()))
}
'{' => {
*pos += 1;
let obj = self.realm.new_object();
skip_ws(c, pos);
if c.get(*pos) == Some(&'}') {
*pos += 1;
return Ok(NanBox::handle(obj.to_raw()));
}
loop {
skip_ws(c, pos);
if c.get(*pos) != Some(&'"') {
return Err(self.json_error("Expected property name"));
}
// Keys live in the `&str`-keyed object layer; a lone surrogate
// in a *key* (an exotic edge) decodes lossily.
let key = crate::wtf8::to_string_lossy(&self.json_string(c, pos)?);
skip_ws(c, pos);
if c.get(*pos) != Some(&':') {
return Err(self.json_error("Expected ':'"));
}
*pos += 1;
let v = self.json_parse(c, pos, depth + 1)?;
self.realm.set_property(obj, &key, v);
skip_ws(c, pos);
match c.get(*pos) {
Some(',') => *pos += 1,
Some('}') => {
*pos += 1;
break;
}
_ => return Err(self.json_error("Expected ',' or '}'")),
}
}
Ok(NanBox::handle(obj.to_raw()))
}
'-' | '0'..='9' => {
let start = *pos;
if c.get(*pos) == Some(&'-') {
*pos += 1;
}
while c
.get(*pos)
.is_some_and(|d| d.is_ascii_digit() || matches!(d, '.' | 'e' | 'E' | '+' | '-'))
{
*pos += 1;
}
let text: String = c[start..*pos].iter().collect();
text.parse::<f64>()
.map(NanBox::number)
.map_err(|_| self.json_error("Invalid number in JSON"))
}
_ => Err(self.json_error("Unexpected token in JSON")),
}
}
/// Like [`Self::json_parse`] but also returns a parallel [`JsonSrc`] tree that
/// records, for every primitive leaf, the value produced and its exact source
/// substring — the raw material for the `json-parse-with-source` reviver
/// `context`. Only invoked when `JSON.parse` is given a callable reviver.
pub(crate) fn json_parse_src(
&mut self,
c: &[char],
pos: &mut usize,
depth: usize,
) -> Result<(NanBox, JsonSrc), ExecError> {
skip_ws(c, pos);
let Some(&ch) = c.get(*pos) else {
return Err(self.json_error("Unexpected end of JSON input"));
};
if matches!(ch, '[' | '{') && depth >= self.realm.limits.max_json_depth {
return Err(self.json_error("Maximum JSON nesting depth exceeded"));
}
// Helper: the source substring `c[start..*pos]` collected as a String.
match ch {
'n' | 't' | 'f' | '"' | '-' | '0'..='9' => {
let start = *pos;
let value = self.json_parse(c, pos, depth)?;
let source: String = c[start..*pos].iter().collect();
Ok((value, JsonSrc::Prim { value, source }))
}
'[' => {
*pos += 1;
let mut elems = Vec::new();
let mut srcs = Vec::new();
skip_ws(c, pos);
if c.get(*pos) == Some(&']') {
*pos += 1;
return Ok((
NanBox::handle(self.realm.new_array(elems).to_raw()),
JsonSrc::Array(srcs),
));
}
loop {
let (v, s) = self.json_parse_src(c, pos, depth + 1)?;
elems.push(v);
srcs.push(s);
skip_ws(c, pos);
match c.get(*pos) {
Some(',') => *pos += 1,
Some(']') => {
*pos += 1;
break;
}
_ => return Err(self.json_error("Expected ',' or ']'")),
}
}
Ok((
NanBox::handle(self.realm.new_array(elems).to_raw()),
JsonSrc::Array(srcs),
))
}
'{' => {
*pos += 1;
let obj = self.realm.new_object();
let mut pairs = Vec::new();
skip_ws(c, pos);
if c.get(*pos) == Some(&'}') {
*pos += 1;
return Ok((NanBox::handle(obj.to_raw()), JsonSrc::Object(pairs)));
}
loop {
skip_ws(c, pos);
if c.get(*pos) != Some(&'"') {
return Err(self.json_error("Expected property name"));
}
let key = crate::wtf8::to_string_lossy(&self.json_string(c, pos)?);
skip_ws(c, pos);
if c.get(*pos) != Some(&':') {
return Err(self.json_error("Expected ':'"));
}
*pos += 1;
let (v, s) = self.json_parse_src(c, pos, depth + 1)?;
self.realm.set_property(obj, &key, v);
// A duplicate key keeps the last value (matching `set_property`);
// record the last source for it too.
if let Some(slot) = pairs
.iter_mut()
.find(|(k, _): &&mut (String, JsonSrc)| k == &key)
{
slot.1 = s;
} else {
pairs.push((key, s));
}
skip_ws(c, pos);
match c.get(*pos) {
Some(',') => *pos += 1,
Some('}') => {
*pos += 1;
break;
}
_ => return Err(self.json_error("Expected ',' or '}'")),
}
}
Ok((NanBox::handle(obj.to_raw()), JsonSrc::Object(pairs)))
}
_ => Err(self.json_error("Unexpected token in JSON")),
}
}
pub(crate) fn json_lit(
&mut self,
c: &[char],
pos: &mut usize,
word: &str,
value: NanBox,
) -> Result<NanBox, ExecError> {
if c[*pos..].iter().take(word.len()).copied().eq(word.chars()) {
*pos += word.len();
Ok(value)
} else {
Err(self.json_error("Unexpected token in JSON"))
}
}
/// Parses a JSON string literal (the opening `"` is at `pos`) into **WTF-8
/// bytes**, preserving lone surrogates (a `\uXXXX` surrogate with no valid
/// partner is kept) and combining `\uXXXX\uXXXX` pairs into the astral scalar.
pub(crate) fn json_string(
&mut self,
c: &[char],
pos: &mut usize,
) -> Result<Vec<u8>, ExecError> {
*pos += 1; // opening quote
let mut out: Vec<u8> = Vec::new();
loop {
match c.get(*pos) {
None => {
return Err(self.json_error("Unterminated string in JSON"));
}
Some('"') => {
*pos += 1;
return Ok(out);
}
Some('\\') => {
*pos += 1;
match c.get(*pos) {
Some('"') => out.push(b'"'),
Some('\\') => out.push(b'\\'),
Some('/') => out.push(b'/'),
Some('n') => out.push(b'\n'),
Some('t') => out.push(b'\t'),
Some('r') => out.push(b'\r'),
Some('b') => out.push(0x08),
Some('f') => out.push(0x0C),
Some('u') => {
let hi = json_hex4(c, *pos + 1)
.ok_or_else(|| self.json_error("Invalid \\u escape in JSON"))?;
*pos += 4;
// A high surrogate may pair with a following `\uXXXX`.
if (0xD800..=0xDBFF).contains(&hi)
&& c.get(*pos + 1) == Some(&'\\')
&& c.get(*pos + 2) == Some(&'u')
&& let Some(lo) = json_hex4(c, *pos + 3)
&& (0xDC00..=0xDFFF).contains(&lo)
{
let cp = 0x1_0000
+ ((u32::from(hi) - 0xD800) << 10)
+ (u32::from(lo) - 0xDC00);
crate::wtf8::encode_code_point(cp, &mut out);
*pos += 6;
} else {
crate::wtf8::encode_utf16_unit(hi, &mut out);
}
}
_ => return Err(self.json_error("Invalid escape in JSON")),
}
*pos += 1;
}
Some(&ch) => {
// A JSONString may not contain an unescaped control character
// (U+0000–U+001F); they must be written as `\n`, `\uXXXX`, etc.
if (ch as u32) < 0x20 {
return Err(
self.json_error("Bad control character in string literal in JSON")
);
}
let mut buf = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
*pos += 1;
}
}
}
}
}
/// A parse-time source-text snapshot mirroring a parsed JSON value's structure,
/// used by the `json-parse-with-source` reviver `context`. Each primitive leaf
/// records the value the parser produced and its exact source substring so the
/// reviver can be handed the original text (unless a reviver has since replaced
/// the value at that position — checked by SameValue).
pub(crate) enum JsonSrc {
Prim { value: NanBox, source: String },
Array(Vec<JsonSrc>),
Object(Vec<(String, JsonSrc)>),
}