quickjs/builtins/json.rs
1//! `JSON`.
2//!
3//! `JSON.stringify` is specified in terms of a *serialisation state* that the
4//! indentation threads through, and the output is compared byte for byte by the
5//! reference test suite — including the trailing-newline-free format with `indent`
6//! and the exact placement of `": "`. That is why the writer below is explicit about
7//! separators rather than leaning on a generic pretty-printer.
8//!
9//! `JSON.parse` accepts the strict JSON grammar; the reference also accepts a few
10//! extensions, but nothing here depends on them.
11
12use crate::builtins::{arg, define_method, install_tag};
13use crate::interp::{Interp, JsResult};
14use crate::object::{JsObject, Property, PropertyKey};
15use crate::value::{Value, number_to_string};
16use js_gc::Gc;
17
18/// Install `JSON`.
19pub fn install(interp: &mut Interp<'_>) {
20 let object_proto = interp.realm.object_proto.clone();
21 let json = interp.new_object(Some(object_proto));
22 // §21.3: `Object.prototype.toString.call(JSON)` is `[object JSON]`.
23 install_tag(&json, "JSON", interp);
24 define_method(&json, "stringify", 3, stringify, interp);
25 define_method(&json, "parse", 2, parse, interp);
26 // The `json-parse-with-source` proposal's other half. Both were absent, and the pair was
27 // filed in the test262 skip list under "engine does not have the feature" — which was
28 // true of these two *methods* and false of the `context.source` argument to a reviver,
29 // so the skip hid 21 cases that had two different causes (`docs/test262-status.md` §4.44).
30 define_method(&json, "rawJSON", 1, raw_json, interp);
31 define_method(&json, "isRawJSON", 1, is_raw_json, interp);
32 let global = interp.realm.global.clone();
33 global.define(
34 "JSON",
35 Property::with_attributes(Value::Object(json), true, false),
36 );
37}
38
39// ---------------------------------------------------------------------------
40// stringify
41// ---------------------------------------------------------------------------
42
43fn stringify(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
44 let value = arg(args, 0);
45 // The second argument restricts or rewrites what is serialised: a function is called for
46 // every key, an array is the list of keys that survive. Ignoring it made
47 // `JSON.stringify({a:1,b:2}, ["a"])` emit both keys.
48 let replacer = Replacer::new(interp, &arg(args, 1))?;
49 // §25.5.2 steps 5–9: the indent is a number of spaces or a string used verbatim, and a
50 // **wrapper** is unwrapped first. Ignoring the wrapper arm meant
51 // `JSON.stringify(x, null, new Number(2))` came out unindented
52 // (`space-number-object`, `space-string-object`) and `new Number(1.5)` was not the two
53 // spaces `ToIntegerOrInfinity` gives it (`space-number-float`).
54 //
55 // The wrapper is unwrapped with **`ToNumber` / `ToString`, not by reading its slot**:
56 // `new Number(1)` whose `valueOf` answers `3` indents by three, and one whose `valueOf`
57 // throws makes `JSON.stringify` throw (`space-number-object` asserts both).
58 let space = arg(args, 2);
59 let space = match &space {
60 Value::Object(wrapper) => match interp.internal_get(wrapper, "_value") {
61 Some(Value::String(_)) => {
62 let text = interp.to_js_string(&space)?;
63 match interp.string(text) {
64 Value::String(text) => Value::String(text),
65 _ => Value::Undefined,
66 }
67 }
68 Some(Value::Int(_) | Value::Float(_)) => Value::Float(interp.to_js_number(&space)?),
69 _ => Value::Undefined,
70 },
71 other => other.clone(),
72 };
73 let indent = match &space {
74 Value::Int(_) | Value::Float(_) => {
75 // `ToIntegerOrInfinity`, then `min(10, …)`.
76 let count = interp.to_js_number(&space)?.trunc().clamp(0.0, 10.0) as usize;
77 " ".repeat(count)
78 }
79 // The first ten **code units**, so an astral character counts as two.
80 Value::String(text) => text
81 .wtf8()
82 .slice_units(0, 10)
83 .to_string_lossy()
84 .into_owned(),
85 _ => String::new(),
86 };
87 let mut out = String::new();
88 let mut stack: Vec<Gc<JsObject>> = Vec::new();
89 let root = make_root_holder(interp, &value)?;
90 match write_value(
91 interp,
92 &mut Writer {
93 out: &mut out,
94 indent: &indent,
95 depth: 0,
96 stack: &mut stack,
97 },
98 &root,
99 &value,
100 "",
101 &replacer,
102 )? {
103 // `undefined`, a function and a symbol serialise to nothing at the top level.
104 true => Ok(interp.string(out)),
105 false => Ok(Value::Undefined),
106 }
107}
108
109/// The `{"": value}` wrapper the spec puts around the root value.
110///
111/// A replacer function is called with this as `this` for the root, and `this[""]` is the
112/// value — which is how a replacer that recurses through `this` gets its starting point.
113fn make_root_holder(interp: &mut Interp<'_>, value: &Value) -> JsResult<Value> {
114 let holder = interp.new_object(None);
115 interp.set_property(&holder, "", value.clone())?;
116 Ok(Value::Object(holder))
117}
118
119/// `JSON.stringify`'s `replacer` argument.
120///
121/// A function is called with the holder and the key; an array names the properties to keep.
122/// Anything else (including `undefined`) is the identity.
123enum Replacer {
124 None,
125 /// The function to call, and the raw value to pass as `this` (the holder).
126 Function(Value),
127 /// The keys to keep, in the order first seen.
128 Keys(Vec<String>),
129}
130
131impl Replacer {
132 fn new(interp: &mut Interp<'_>, value: &Value) -> JsResult<Replacer> {
133 let Value::Object(object) = value else {
134 return Ok(Replacer::None);
135 };
136 if object.is_callable() {
137 return Ok(Replacer::Function(value.clone()));
138 }
139 if !object.is_array() {
140 return Ok(Replacer::None);
141 }
142 // §25.5.2 step 4.a: `LengthOfArrayLike(replacer)` — `Get(replacer, "length")` then
143 // `ToLength`, both script-visible. `array_length()` answers `None` for a **proxy**,
144 // which made `JSON.stringify(x, new Proxy(["b"], {}))` emit `{}`.
145 let length = match interp.get_property(object, "length")? {
146 None | Some(Value::Undefined) => 0,
147 Some(value) => {
148 let number = interp.to_js_number(&value)?;
149 if number.is_nan() || number <= 0.0 {
150 0
151 } else {
152 number.min(9_007_199_254_740_991.0) as usize
153 }
154 }
155 };
156 let mut keys: Vec<String> = Vec::new();
157 for index in 0..length {
158 let Some(element) = interp.get_property(object, &index.to_string())? else {
159 continue;
160 };
161 // 4.a.iv: a String contributes itself; a Number or BigInt is `ToString`'d; a
162 // String/Number/BigInt **wrapper** is `ToString`'d as well. The wrapper arm was
163 // missing, so `JSON.stringify({a: 2}, [new String("a")])` emitted `{}`.
164 let text = match &element {
165 Value::String(text) => text.to_string_lossy().to_string(),
166 Value::Int(_) | Value::Float(_) | Value::BigInt(_) => {
167 interp.to_js_string(&element)?
168 }
169 Value::Object(wrapper) => match interp.internal_get(wrapper, "_value") {
170 Some(Value::String(_) | Value::Int(_) | Value::Float(_) | Value::BigInt(_)) => {
171 interp.to_js_string(&element)?
172 }
173 _ => continue,
174 },
175 _ => continue,
176 };
177 if !keys.contains(&text) {
178 keys.push(text);
179 }
180 }
181 Ok(Replacer::Keys(keys))
182 }
183
184 /// The `PropertyList` an array replacer builds, in its own order.
185 ///
186 /// `SerializeJSONObject` walks this list rather than the object's own keys, which is
187 /// the only way `JSON.stringify({a:1,b:2,c:3}, ["c","b","a"])` can answer
188 /// `{"c":3,"b":2,"a":1}` — filtering the object's keys kept insertion order
189 /// (`replacer-array-order`).
190 fn property_list(&self) -> Option<&[String]> {
191 match self {
192 Replacer::Keys(keys) => Some(keys),
193 _ => None,
194 }
195 }
196
197 /// `SerializeJSONProperty`'s replacer step: the function replaces the value.
198 fn apply(
199 &self,
200 interp: &mut Interp<'_>,
201 holder: &Value,
202 value: &Value,
203 key: &str,
204 ) -> JsResult<Value> {
205 let Replacer::Function(function) = self else {
206 return Ok(value.clone());
207 };
208 interp.call_value(
209 function.clone(),
210 holder.clone(),
211 vec![interp.string(key), value.clone()],
212 )
213 }
214}
215
216/// Serialise `value` into `out`. Returns whether anything was written, which is how
217/// a top-level `undefined` becomes the value `undefined` rather than `"undefined"`.
218///
219/// `key` is the property name the value was read from, which `toJSON` receives; the
220/// root value is passed the empty string, as the spec's wrapper object does.
221/// The primitive inside a wrapper object, or the value unchanged.
222///
223/// `_value` is the slot this engine's `new Number(x)` and `Object(x)` fill in, so it is
224/// the same thing the spec's internal slots carry.
225fn unwrap_primitive_wrapper(interp: &Interp<'_>, value: &Value) -> Value {
226 let Some(object) = value.as_object() else {
227 return value.clone();
228 };
229 let Some(inner) = interp.internal_get(object, "_value") else {
230 return value.clone();
231 };
232 // Only a box of a *primitive*: an ordinary object that happens to have `_value` must
233 // keep serialising as an object.
234 match inner {
235 Value::Int(_) | Value::Float(_) | Value::String(_) | Value::Bool(_) | Value::BigInt(_) => {
236 inner
237 }
238 _ => value.clone(),
239 }
240}
241
242/// The verbatim JSON text of a `[[IsRawJSON]]` object, if that is what `object` is.
243fn raw_json_text(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
244 let marker = interp.internal_get(object, "_is_raw_json")?;
245 if !marker.to_boolean() {
246 return None;
247 }
248 let text = object.own_property("rawJSON")?.value?;
249 Some(text.to_js_string())
250}
251
252/// Where the text is being written: the buffer, the indent unit and how deep the current
253/// value sits. Grouped so `write_value` keeps a readable argument list.
254struct Writer<'a> {
255 out: &'a mut String,
256 indent: &'a str,
257 depth: usize,
258 /// `SerializeJSONProperty`'s `stack`: the objects currently being serialised, root
259 /// first. Meeting one twice means the value graph has a cycle, and the spec makes that
260 /// a `TypeError` rather than an attempt to describe the loop.
261 ///
262 /// Without this the recursion below ran off the *Rust* stack and aborted the whole
263 /// process — no JS-level limit could stop it, because the recursion was in the host.
264 stack: &'a mut Vec<Gc<JsObject>>,
265}
266
267fn write_value(
268 interp: &mut Interp<'_>,
269 writer: &mut Writer<'_>,
270 holder: &Value,
271 value: &Value,
272 key: &str,
273 replacer: &Replacer,
274) -> JsResult<bool> {
275 // `out` and `stack` are separate fields, so borrowing both at once is fine.
276 let Writer {
277 out,
278 indent,
279 depth,
280 stack,
281 } = writer;
282 let (indent, depth) = (*indent, *depth);
283 // The array form does **not** filter here: its `PropertyList` decides which keys
284 // `SerializeJSONObject` walks at all (see `write_object`), while an *array* serialises
285 // every position regardless. Filtering by key at this level made
286 // `JSON.stringify([1, {}], [])` emit `[null,null]`.
287 // A value carrying a `toJSON` method is replaced by whatever that returns, and
288 // the replacement is not asked for `toJSON` again. This is how a `Date`
289 // serialises to its ISO string.
290 let value = &call_to_json(interp, value, key)?;
291 // A replacer *function* receives the value after `toJSON` and may replace it outright.
292 // `this` is the holder — the object or array the value was read from — because a
293 // replacer commonly reads sibling properties through `this[key]`.
294 let value = &replacer.apply(interp, holder, value, key)?;
295 // A wrapper object serialises as the primitive it wraps: `JSON.stringify(Object(1))`
296 // is `"1"`, not `"{}"`. SerialiseJSONProperty unwraps `[[NumberData]]`,
297 // `[[StringData]]`, `[[BooleanData]]` and `[[BigIntData]]` before looking at the
298 // object's enumerable keys, and a wrapper has none of its own — which is why skipping
299 // the step printed an empty object.
300 let value = &unwrap_primitive_wrapper(interp, value);
301 // A value carrying `[[IsRawJSON]]` is emitted verbatim, after `toJSON` and the replacer
302 // have had their say — `JSON.stringify({toJSON: () => JSON.rawJSON(3)})` is `"3"`, and
303 // a replacer that returns a rawJSON object gets the same treatment.
304 if let Value::Object(object) = value
305 && let Some(text) = raw_json_text(interp, object)
306 {
307 out.push_str(&text);
308 return Ok(true);
309 }
310 match value {
311 // A symbol serialises to nothing, exactly like `undefined`: `JSON.stringify`
312 // drops it from an object and answers `undefined` for it at the top level.
313 // A bigint has no JSON form, and the spec makes that an error rather than a
314 // silent omission — losing a number is not the same as losing `undefined`.
315 Value::BigInt(_) => Err(interp.type_error("BigInt value can't be serialized in JSON")),
316 Value::Undefined
317 | Value::Symbol(_)
318 | Value::Uninitialized
319 | Value::Hole
320 | Value::CatchOffset(_)
321 | Value::ReturnAddress(_) => Ok(false),
322 Value::Null => {
323 out.push_str("null");
324 Ok(true)
325 }
326 Value::Bool(value) => {
327 out.push_str(if *value { "true" } else { "false" });
328 Ok(true)
329 }
330 Value::Int(_) | Value::Float(_) => {
331 let number = value.to_number();
332 // `NaN` and the infinities serialise as `null`.
333 if number.is_finite() {
334 out.push_str(&number_to_string(number));
335 } else {
336 out.push_str("null");
337 }
338 Ok(true)
339 }
340 Value::String(text) => {
341 write_string(text.wtf8(), out);
342 Ok(true)
343 }
344 Value::Object(object) => {
345 if object.is_callable() {
346 return Ok(false);
347 }
348 // `SerializeJSONProperty`: an object already on the stack is a cycle, and the
349 // spec turns that into a `TypeError`. The comparison is by identity, so two
350 // separate but equal objects are fine — only a genuine loop is rejected.
351 //
352 // Checked here rather than in `write_array`/`write_object` so both share one
353 // rule, and *before* descending so a self-referential root is caught at depth 1
354 // instead of after the first level of recursion.
355 if stack.iter().any(|seen| seen.ptr_eq(object)) {
356 return Err(interp.type_error("circular reference"));
357 }
358 stack.push(object.clone());
359 let result = if object.is_array() {
360 write_array(
361 interp,
362 &mut Writer {
363 out,
364 indent,
365 depth,
366 stack,
367 },
368 object,
369 replacer,
370 )
371 } else {
372 write_object(
373 interp,
374 &mut Writer {
375 out,
376 indent,
377 depth,
378 stack,
379 },
380 object,
381 replacer,
382 )
383 };
384 stack.pop();
385 result?;
386 Ok(true)
387 }
388 }
389}
390
391/// `SerializeJSONProperty`'s `toJSON` step, applied once.
392fn call_to_json(interp: &mut Interp<'_>, value: &Value, key: &str) -> JsResult<Value> {
393 let Value::Object(object) = value else {
394 return Ok(value.clone());
395 };
396 let Some(method) = interp.get_property(object, "toJSON")? else {
397 return Ok(value.clone());
398 };
399 if !matches!(&method, Value::Object(function) if function.is_callable()) {
400 return Ok(value.clone());
401 }
402 interp.call_value(method, value.clone(), vec![interp.string(key)])
403}
404
405fn write_array(
406 interp: &mut Interp<'_>,
407 writer: &mut Writer<'_>,
408 array: &Gc<JsObject>,
409 replacer: &Replacer,
410) -> JsResult<()> {
411 let Writer {
412 out,
413 indent,
414 depth,
415 stack,
416 } = writer;
417 let (indent, depth) = (*indent, *depth);
418 // `LengthOfArrayLike`. A plain array answers from its slot; a **proxy** over one has no
419 // slot of its own, so the length comes through `[[Get]]`, which forwards to the target —
420 // reading `array_length()` and defaulting to 0 made
421 // `JSON.stringify(new Proxy([0,1], {}))` emit `[]` (`value-array-proxy`).
422 let length = match array.array_length() {
423 Some(length) => length,
424 None => match interp.get_property(array, "length")? {
425 None | Some(Value::Undefined) => 0,
426 Some(value) => {
427 let number = interp.to_js_number(&value)?;
428 if number.is_nan() || number <= 0.0 {
429 0
430 } else {
431 number.min(9_007_199_254_740_991.0) as usize
432 }
433 }
434 },
435 };
436 if length == 0 {
437 out.push_str("[]");
438 return Ok(());
439 }
440 out.push('[');
441 for index in 0..length {
442 if index > 0 {
443 out.push(',');
444 }
445 newline(out, indent, depth + 1);
446 // `[[Get]]`, not the element vector: an accessor defined on an index lives in the
447 // property table and the slot it shadows is a hole, so reading the vector directly
448 // printed `null` for `Object.defineProperty(a, "0", {get})`.
449 let element = match array.array_get(index) {
450 Some(Value::Hole) | None => interp
451 .get_property_key(array, &PropertyKey::from(index.to_string()))?
452 .unwrap_or(Value::Undefined),
453 Some(value) => value,
454 };
455 // A hole or an unserialisable element becomes `null`, because an array's
456 // positions are part of its meaning.
457 if !write_value(
458 interp,
459 &mut Writer {
460 out,
461 indent,
462 depth: depth + 1,
463 stack,
464 },
465 &Value::Object(array.clone()),
466 &element,
467 &index.to_string(),
468 replacer,
469 )? {
470 out.push_str("null");
471 }
472 }
473 newline(out, indent, depth);
474 out.push(']');
475 Ok(())
476}
477
478fn write_object(
479 interp: &mut Interp<'_>,
480 writer: &mut Writer<'_>,
481 object: &Gc<JsObject>,
482 replacer: &Replacer,
483) -> JsResult<()> {
484 let Writer {
485 out,
486 indent,
487 depth,
488 stack,
489 } = writer;
490 let (indent, depth) = (*indent, *depth);
491 // Enumerable own keys in the spec's order, skipping keys whose values do not
492 // serialise (a function-valued property is omitted, not `null`).
493 //
494 // Through `[[OwnPropertyKeys]]` and `[[GetOwnProperty]]`, so a proxy serialises as
495 // its handler describes it: reading the property table directly made
496 // `JSON.stringify(proxy)` emit `{}` for every proxy.
497 let mut keys: Vec<crate::object::PropertyKey> = Vec::new();
498 // With an array replacer the walk order is the replacer's, and an own key it does not
499 // name is never visited at all.
500 if let Some(list) = replacer.property_list() {
501 for name in list {
502 keys.push(crate::object::PropertyKey::from(name.as_str()));
503 }
504 }
505 for key in if replacer.property_list().is_some() {
506 Vec::new()
507 } else {
508 interp.object_own_property_keys(object)?
509 } {
510 if key.is_symbol() {
511 // A symbol-keyed property is invisible to `JSON.stringify`.
512 continue;
513 }
514 let enumerable = interp
515 .object_get_own_property(object, &key)?
516 .is_some_and(|property| property.enumerable);
517 if enumerable {
518 keys.push(key);
519 }
520 }
521 let mut written = 0usize;
522 let mut body = String::new();
523 for key in keys {
524 // Two views of the same key: the replacer's plumbing takes a `&str` (it compares
525 // against the replacer array and hands the key to a user function), while the
526 // emitted JSON must keep the key's own code units — a key may hold an unpaired
527 // surrogate, and flattening it here would print a different property name.
528 let key_text = key.as_str().unwrap_or_default().to_string();
529 let key_json = key.as_wtf8().cloned().unwrap_or_default();
530 let Some(value) = interp.get_property_key(object, &key)? else {
531 continue;
532 };
533 let mut piece = String::new();
534 // Render the value first so an unrepresentable one can be skipped whole.
535 if !write_value(
536 interp,
537 &mut Writer {
538 out: &mut piece,
539 indent,
540 depth: depth + 1,
541 stack,
542 },
543 &Value::Object(object.clone()),
544 &value,
545 &key_text,
546 replacer,
547 )? {
548 continue;
549 }
550 if written > 0 {
551 body.push(',');
552 }
553 newline(&mut body, indent, depth + 1);
554 let mut escaped = String::new();
555 write_string(&key_json, &mut escaped);
556 body.push_str(&escaped);
557 body.push(':');
558 if !indent.is_empty() {
559 body.push(' ');
560 }
561 body.push_str(&piece);
562 written += 1;
563 }
564 if written == 0 {
565 out.push_str("{}");
566 return Ok(());
567 }
568 out.push('{');
569 out.push_str(&body);
570 newline(out, indent, depth);
571 out.push('}');
572 Ok(())
573}
574
575/// Emit the indentation for one level, or nothing when not pretty-printing.
576fn newline(out: &mut String, indent: &str, depth: usize) {
577 if indent.is_empty() {
578 return;
579 }
580 out.push('\n');
581 for _ in 0..depth {
582 out.push_str(indent);
583 }
584}
585
586/// Write `text` as a JSON string literal.
587///
588/// The escapes are the spec's twenty-odd: the two mandatory ones, the two that are
589/// required for well-formed JSON in a script (`\u2028`/`\u2029`), and control
590/// characters below `0x20` as `\u00XX`.
591fn write_string(text: &crate::value::Wtf8, out: &mut String) {
592 out.push('"');
593 // Code *units*, because a string may hold an unpaired surrogate and JSON requires one
594 // to be written as `\udXXX` rather than dropped or replaced by U+FFFD. A valid pair is
595 // folded back into its astral character, which is what the reference prints and what
596 // keeps well-formed text readable in the output.
597 let units = text.to_units();
598 let mut index = 0;
599 while index < units.len() {
600 let unit = units[index];
601 if (0xD800..0xDC00).contains(&unit)
602 && let Some(&low) = units.get(index + 1)
603 && (0xDC00..0xE000).contains(&low)
604 {
605 let code = 0x10000 + ((u32::from(unit) - 0xD800) << 10) + (u32::from(low) - 0xDC00);
606 write_char(char::from_u32(code).unwrap_or('\u{fffd}'), out);
607 index += 2;
608 continue;
609 }
610 if (0xD800..0xE000).contains(&unit) {
611 out.push_str(&format!("\\u{unit:04x}"));
612 index += 1;
613 continue;
614 }
615 write_char(char::from_u32(u32::from(unit)).unwrap_or('\u{fffd}'), out);
616 index += 1;
617 }
618 out.push('"');
619}
620
621/// One non-surrogate code unit's escape.
622fn write_char(character: char, out: &mut String) {
623 match character {
624 '"' => out.push_str("\\\""),
625 '\\' => out.push_str("\\\\"),
626 '\n' => out.push_str("\\n"),
627 '\r' => out.push_str("\\r"),
628 '\t' => out.push_str("\\t"),
629 '\u{8}' => out.push_str("\\b"),
630 '\u{c}' => out.push_str("\\f"),
631 c if (c as u32) < 0x20 => {
632 out.push_str(&format!("\\u{:04x}", c as u32));
633 }
634 c => out.push(c),
635 }
636}
637
638/// `JSON.rawJSON(value)` — a value whose JSON spelling is given verbatim.
639///
640/// The point is round-tripping what a JS number cannot hold: `JSON.stringify` of
641/// `JSON.rawJSON("9007199254740993")` emits exactly those digits instead of the
642/// `9007199254740992` the double rounds to.
643///
644/// The argument must stringify to a single JSON **primitive**. `"[1]"`, `"{}"` and `"1 2"`
645/// are all `SyntaxError`s — "a parser accepted this text" is weaker than the spec, which
646/// asks for exactly one primitive parse node.
647fn raw_json(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
648 // `ToString` first, so a symbol is a `TypeError` (from the conversion) rather than a
649 // `SyntaxError` about the text it never produced.
650 let text = interp.checked_to_string(&arg(args, 0))?;
651 if text.is_empty() || !is_json_primitive_text(&text) {
652 return Err(crate::interp::Signal::Throw(
653 interp.make_error("SyntaxError", "invalid JSON primitive"),
654 ));
655 }
656 // `OrdinaryObjectCreate(null)`: a data key called `toString` must not collide with a
657 // method, and the suite asserts the prototype is `null` and that `rawJSON` is the only
658 // own property.
659 let object = interp.new_object(None);
660 object.define(
661 "rawJSON",
662 Property::with_attributes(interp.string(text), true, true),
663 );
664 // Not a visible property: `[[IsRawJSON]]` has to be unforgeable, or
665 // `JSON.isRawJSON({rawJSON: "123"})` would answer `true`.
666 interp.internal_set(&object, "_is_raw_json", Value::Bool(true));
667 Ok(Value::Object(object))
668}
669
670/// Whether `text` is exactly one JSON primitive: a number, a string, `true`, `false` or
671/// `null`, with no surrounding whitespace.
672///
673/// Reuses the real parser rather than a hand-rolled accept/reject, so `"1e"`, `"01"` and
674/// `"\u12"` are rejected for the same reasons `JSON.parse` rejects them. The extension flag
675/// is off: `rawJSON(Infinity)` must be a `SyntaxError`.
676fn is_json_primitive_text(text: &str) -> bool {
677 let mut parser = Parser {
678 bytes: text.as_bytes(),
679 text,
680 position: 0,
681 ext: false,
682 // No reviver can ever see this tree, so there is nothing to record.
683 track: false,
684 last_span: (0, 0),
685 };
686 json_primitive_text(&mut parser)
687}
688
689/// The parser half of [`is_json_primitive_text`], split out so it can run without an
690/// `Interp`.
691///
692/// `Parser::value_inner` needs an `Interp` for the string and container cases. A scan that
693/// answers the same question without allocating is 30 lines and avoids the interpreter
694/// entirely, so it cannot run a getter or grow the heap.
695fn json_primitive_text(parser: &mut Parser<'_>) -> bool {
696 let text = parser.text;
697 if text.is_empty() || text.trim() != text {
698 return false;
699 }
700 // A string literal: quoted, and the closing quote is the last byte.
701 if text.starts_with('"') {
702 if !text.ends_with('"') || text.len() < 2 {
703 return false;
704 }
705 return valid_json_string(&text[1..text.len() - 1]);
706 }
707 if text == "true" || text == "false" || text == "null" {
708 return true;
709 }
710 parser.position = 0;
711 parser.number().is_ok() && parser.position == text.len()
712}
713
714/// Whether `body` is a run of JSON string content: no raw control characters, no lone
715/// backslash, and every `\u` escape followed by four hex digits.
716fn valid_json_string(body: &str) -> bool {
717 let bytes = body.as_bytes();
718 let mut index = 0;
719 while index < bytes.len() {
720 match bytes[index] {
721 b'"' => return false,
722 b'\\' => {
723 index += 1;
724 match bytes.get(index) {
725 Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => index += 1,
726 Some(b'u') => {
727 index += 1;
728 for _ in 0..4 {
729 match bytes.get(index) {
730 Some(byte) if byte.is_ascii_hexdigit() => index += 1,
731 _ => return false,
732 }
733 }
734 }
735 _ => return false,
736 }
737 }
738 byte if byte < 0x20 => return false,
739 byte => index += utf8_len(byte),
740 }
741 }
742 true
743}
744
745fn utf8_len(first: u8) -> usize {
746 match first {
747 0x00..=0x7f => 1,
748 0xc0..=0xdf => 2,
749 0xe0..=0xef => 3,
750 _ => 4,
751 }
752}
753
754/// `JSON.isRawJSON(value)` — true only for an object carrying `[[IsRawJSON]]`.
755fn is_raw_json(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
756 let is_raw = match arg(args, 0) {
757 Value::Object(object) => interp
758 .internal_get(&object, "_is_raw_json")
759 .is_some_and(|marker| marker.to_boolean()),
760 _ => false,
761 };
762 Ok(Value::Bool(is_raw))
763}
764
765// ---------------------------------------------------------------------------
766// parse
767// ---------------------------------------------------------------------------
768
769/// Parse `text`, either as RFC 8259 JSON or in the extended dialect.
770///
771/// The extended dialect is what the reference calls `JS_PARSE_JSON_EXT`: the same parser
772/// with a flag, not a separate parser and not a pre-processing pass. It is exposed to
773/// scripts only through `std.parseExtJSON`, so `JSON.parse` stays strict.
774pub fn parse_text(interp: &mut Interp<'_>, text: &str, ext: bool) -> JsResult<Value> {
775 parse_text_tracking(interp, text, ext, false)
776}
777
778/// [`parse_text`], optionally recording each primitive's source text.
779///
780/// The public `parse_text` never tracks: `std.parseExtJSON` has no reviver, so the source
781/// table would always be dead weight.
782fn parse_text_tracking(
783 interp: &mut Interp<'_>,
784 text: &str,
785 ext: bool,
786 track: bool,
787) -> JsResult<Value> {
788 let mut parser = Parser {
789 bytes: text.as_bytes(),
790 text,
791 position: 0,
792 ext,
793 track,
794 last_span: (0, 0),
795 };
796 parser.skip_whitespace();
797 let value = match parser.value(interp) {
798 Ok(value) => value,
799 Err(error) => {
800 return Err(crate::interp::Signal::Throw(json_error(
801 interp, text, error,
802 )));
803 }
804 };
805 parser.skip_whitespace();
806 if parser.position != parser.bytes.len() {
807 return Err(crate::interp::Signal::Throw(json_error(
808 interp,
809 text,
810 JsonError {
811 message: "unexpected data after JSON value".to_string(),
812 offset: parser.position,
813 },
814 )));
815 }
816 Ok(value)
817}
818
819fn parse(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
820 // `ToString(text)` — through `ToPrimitive`, so an object with a `toString` is parsed
821 // from what that returns (and a symbol is a `TypeError`, not a `SyntaxError`).
822 //
823 // `Value::to_js_string` is the total convertor, and using it here made
824 // `JSON.parse({toString: () => '"s"'})` a `SyntaxError`: the object's own spelling is
825 // `[object Object]`, which no parser accepts.
826 let text = interp.checked_to_string(&arg(args, 0))?;
827 // The second argument rewrites the parsed tree bottom-up. Ignoring it made
828 // `JSON.parse('{"a":1}', (k, v) => v * 2).a` answer `1`.
829 let reviver = arg(args, 1);
830 let is_reviver = matches!(&reviver, Value::Object(function) if function.is_callable());
831 // Source text is only recorded when a reviver can observe it: `context.source` is the
832 // one place the original spelling of a number survives (`1.0` parses to `1` but its
833 // source is `"1.0"`), and without a reviver there is nobody to ask.
834 let value = parse_text_tracking(interp, &text, false, is_reviver)?;
835 if !is_reviver {
836 return Ok(value);
837 }
838 // `InternalizeJSONProperty` starts from `{"": value}`, so the root is visited last and
839 // may itself be replaced.
840 let root = make_root_holder(interp, &value)?;
841 let Value::Object(root) = &root else {
842 return Ok(value);
843 };
844 // A primitive root has no container to carry its source, so it goes on the holder
845 // under the empty key — which is the key the reviver sees for the root.
846 if value.as_object().is_none() {
847 let table = interp.new_object(None);
848 table.define_data("", interp.string(text.trim()));
849 interp.internal_set(root, "_json_source", Value::Object(table));
850 }
851 internalize_json_property(interp, root, "", &reviver)
852}
853
854/// `CreateDataProperty`, which differs from `Set` in exactly the case a reviver hits: an
855/// existing non-configurable property keeps its value instead of being overwritten, and the
856/// refusal is not an error.
857fn create_data_property(
858 interp: &mut Interp<'_>,
859 object: &Gc<JsObject>,
860 key: &str,
861 value: Value,
862) -> JsResult<()> {
863 let key = crate::object::PropertyKey::from(key);
864 // A property that already exists and cannot be redefined keeps its old value: the
865 // definition is refused rather than applied. `Object.defineProperty` would report that
866 // refusal through its return value, but here a reviver that froze a property while
867 // visiting an earlier key must simply see it stay frozen.
868 if interp
869 .object_get_own_property(object, &key)?
870 .is_some_and(|existing| !existing.configurable)
871 {
872 return Ok(());
873 }
874 let property = crate::object::Property {
875 value: Some(value),
876 writable: true,
877 enumerable: true,
878 configurable: true,
879 ..crate::object::Property::default()
880 };
881 interp.object_define_own_property(object, &key, property)?;
882 Ok(())
883}
884
885/// `InternalizeJSONProperty`: call the reviver on every property, depth first, and drop the
886/// ones it answers `undefined` for.
887fn internalize_json_property(
888 interp: &mut Interp<'_>,
889 holder: &Gc<JsObject>,
890 key: &str,
891 reviver: &Value,
892) -> JsResult<Value> {
893 let Some(value) = interp.get_property(holder, key)? else {
894 return Ok(Value::Undefined);
895 };
896 // Arrays are walked by index and objects by their enumerable own keys; a primitive has
897 // nothing to walk, so it goes straight to the call.
898 if let Value::Object(object) = &value {
899 if object.is_array() {
900 // §25.5.1.1 step 2.a.i: `LengthOfArrayLike(val)`, which is `Get(val, "length")`
901 // followed by `ToLength` — both script-visible. Reading the internal slot
902 // instead answered `0` for a **proxy** over an array (whose own slot is empty),
903 // so the walk skipped an element entirely: `reviver-array-delete-err` plants a
904 // proxy in the array and expects its `deleteProperty` trap to run. A `length`
905 // getter or a `valueOf` in the length likewise has to run
906 // (`reviver-array-length-get-err`, `reviver-array-length-coerce-err`).
907 let length = match interp.get_property(object, "length")? {
908 None | Some(Value::Undefined) => 0,
909 Some(value) => {
910 let number = interp.to_js_number(&value)?;
911 if number.is_nan() || number <= 0.0 {
912 0
913 } else {
914 number.min(9_007_199_254_740_991.0) as usize
915 }
916 }
917 };
918 for index in 0..length {
919 let element_key = index.to_string();
920 let replaced = internalize_json_property(interp, object, &element_key, reviver)?;
921 if matches!(replaced, Value::Undefined) {
922 interp.delete_property(object, &element_key)?;
923 } else {
924 // `CreateDataProperty`, not `Set`: when the property already exists and
925 // refuses redefinition the new value is dropped. A reviver that froze a
926 // property while visiting an earlier key must not have it overwritten by
927 // a later branch.
928 create_data_property(interp, object, &element_key, replaced)?;
929 }
930 }
931 } else {
932 for name in interp.object_own_property_keys(object)? {
933 let Some(name) = name.as_str() else {
934 continue;
935 };
936 let name = name.to_string();
937 let replaced = internalize_json_property(interp, object, &name, reviver)?;
938 if matches!(replaced, Value::Undefined) {
939 interp.delete_property(object, &name)?;
940 } else {
941 create_data_property(interp, object, &name, replaced)?;
942 }
943 }
944 }
945 }
946 // `context`: a plain object, with `source` **only** when the value is a primitive
947 // (§`InternalizeJSONProperty`). The property is created with
948 // `CreateDataProperty`-attributes — writable, enumerable, configurable — which the
949 // suite checks one by one.
950 let context = interp.new_object(Some(interp.realm.object_proto.clone()));
951 if value.as_object().is_none()
952 && let Some(source) = json_source_of(interp, holder, key)
953 {
954 context.define("source", Property::with_attributes(source, true, true));
955 }
956 interp.call_value(
957 reviver.clone(),
958 Value::Object(holder.clone()),
959 vec![interp.string(key), value, Value::Object(context)],
960 )
961}
962
963/// The source text recorded for `holder[key]`, if any.
964fn json_source_of(interp: &Interp<'_>, holder: &Gc<JsObject>, key: &str) -> Option<Value> {
965 let table = interp.internal_get(holder, "_json_source")?;
966 let table = table.as_object()?;
967 table.own_property(key).and_then(|property| property.value)
968}
969
970/// A `SyntaxError` that reports where in the JSON text parsing failed.
971///
972/// The reference builds these with an explicit position, so the trace starts with
973/// ` at <input>:line:column` — the position inside the text — and only then lists
974/// the caller. `<input>` is the reference's placeholder for text that came from a
975/// string rather than a file, so it is kept even when the caller is a real script.
976fn json_error(interp: &mut Interp<'_>, text: &str, error: JsonError) -> Value {
977 let (line, column) = line_and_column(text, error.offset);
978 let trace = format!(" at <input>:{line}:{column}\n{}", interp.stack_trace());
979 let value = interp.make_error("SyntaxError", &error.message);
980 if let Value::Object(object) = &value {
981 let text = interp.string(trace);
982 object.define(
983 "stack",
984 crate::object::Property::with_attributes(text, true, true),
985 );
986 }
987 value
988}
989
990/// The 1-based line and column of `offset` in `text`.
991///
992/// Columns count UTF-16 code units, like every other position in this engine, so a
993/// character outside the BMP counts twice.
994fn line_and_column(text: &str, offset: usize) -> (usize, usize) {
995 let before = &text[..offset.min(text.len())];
996 let line = before.matches('\n').count() + 1;
997 let line_start = before.rfind('\n').map_or(0, |index| index + 1);
998 let column = before[line_start..].encode_utf16().count() + 1;
999 (line, column)
1000}
1001
1002/// A JSON syntax error and where in the JSON text it happened.
1003///
1004/// The offset is what lets `JSON.parse` report a position the way the reference does:
1005/// its stack starts with the line and column inside the *text being parsed*, not with
1006/// the caller's frame.
1007struct JsonError {
1008 message: String,
1009 offset: usize,
1010}
1011
1012struct Parser<'a> {
1013 bytes: &'a [u8],
1014 text: &'a str,
1015 position: usize,
1016 /// Whether the extended dialect is in force. Every relaxation below is gated on it, so
1017 /// `JSON.parse` keeps rejecting what RFC 8259 rejects.
1018 ext: bool,
1019 /// Whether to record the source text of primitive values.
1020 ///
1021 /// Only needed when a reviver is present, because `reviver(key, value, {source})` is the
1022 /// one place the text is observable. Recording is on the *parser* rather than a second
1023 /// pass so the slice is exact: a re-parse would have to guess, and `1.0` versus `1`
1024 /// would be a coin flip.
1025 track: bool,
1026 /// The byte span of the value [`Parser::value`] returned most recently.
1027 last_span: (usize, usize),
1028}
1029
1030/// Whether `text` matches RFC 8259's `number` production exactly.
1031///
1032/// (RFC 8259 §6: `int` is `0` or a nonzero digit followed by digits, `frac` needs a digit
1033/// after the point, and `exp` needs one after the `e`.)
1034fn is_rfc_number(text: &str) -> bool {
1035 let bytes = text.as_bytes();
1036 let mut index = 0;
1037 if bytes.first() == Some(&b'-') {
1038 index += 1;
1039 }
1040 // `int`: a lone `0`, or a nonzero digit and then any digits.
1041 match bytes.get(index) {
1042 Some(b'0') => index += 1,
1043 Some(b'1'..=b'9') => {
1044 index += 1;
1045 while bytes.get(index).is_some_and(u8::is_ascii_digit) {
1046 index += 1;
1047 }
1048 }
1049 _ => return false,
1050 }
1051 // `frac`: the point needs at least one digit after it.
1052 if bytes.get(index) == Some(&b'.') {
1053 index += 1;
1054 let digits = index;
1055 while bytes.get(index).is_some_and(u8::is_ascii_digit) {
1056 index += 1;
1057 }
1058 if index == digits {
1059 return false;
1060 }
1061 }
1062 // `exp`: likewise.
1063 if matches!(bytes.get(index), Some(b'e' | b'E')) {
1064 index += 1;
1065 if matches!(bytes.get(index), Some(b'+' | b'-')) {
1066 index += 1;
1067 }
1068 let digits = index;
1069 while bytes.get(index).is_some_and(u8::is_ascii_digit) {
1070 index += 1;
1071 }
1072 if index == digits {
1073 return false;
1074 }
1075 }
1076 index == bytes.len()
1077}
1078
1079/// Whether `byte` may start a bare identifier key: the reference's `TOK_IDENT` start set.
1080fn is_identifier_start(byte: u8) -> bool {
1081 byte.is_ascii_alphabetic() || byte == b'_' || byte == b'$'
1082}
1083
1084impl Parser<'_> {
1085 /// An error blamed on the parser's current position.
1086 fn error<T>(&self, message: impl Into<String>) -> Result<T, JsonError> {
1087 Err(JsonError {
1088 message: message.into(),
1089 offset: self.position,
1090 })
1091 }
1092
1093 fn skip_whitespace(&mut self) {
1094 loop {
1095 while let Some(byte) = self.bytes.get(self.position) {
1096 match byte {
1097 b' ' | b'\t' | b'\n' | b'\r' => self.position += 1,
1098 // `JSONWhitespace` does not match <VT> or <FF>; the extended dialect
1099 // does, so `formfeed` and `vertical tab` count as space there.
1100 b'\x0b' | b'\x0c' if self.ext => self.position += 1,
1101 _ => break,
1102 }
1103 }
1104 // Comments are whitespace in the extended dialect, and they may abut each other,
1105 // so this is a loop rather than one check.
1106 if !self.ext || !self.skip_one_comment() {
1107 return;
1108 }
1109 }
1110 }
1111
1112 /// Skip one `/* … */` or `// …` comment, reporting whether there was one.
1113 ///
1114 /// An unterminated block comment leaves the position at the end, so the caller reports
1115 /// "unexpected end of JSON input" instead of silently accepting a truncated document.
1116 fn skip_one_comment(&mut self) -> bool {
1117 if self.bytes.get(self.position) != Some(&b'/') {
1118 return false;
1119 }
1120 match self.bytes.get(self.position + 1) {
1121 Some(b'*') => {
1122 self.position += 2;
1123 while self.position < self.bytes.len() {
1124 if self.bytes[self.position..].starts_with(b"*/") {
1125 self.position += 2;
1126 return true;
1127 }
1128 self.position += 1;
1129 }
1130 true
1131 }
1132 Some(b'/') => {
1133 self.position += 2;
1134 // A line comment ends at CR, LF, or a Unicode line separator.
1135 while let Some(character) = self.text[self.position..].chars().next() {
1136 if matches!(character, '\r' | '\n' | '\u{2028}' | '\u{2029}') {
1137 break;
1138 }
1139 self.position += character.len_utf8();
1140 }
1141 true
1142 }
1143 _ => false,
1144 }
1145 }
1146
1147 fn peek(&self) -> Option<u8> {
1148 self.bytes.get(self.position).copied()
1149 }
1150
1151 fn value(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
1152 self.skip_whitespace();
1153 let start = self.position;
1154 let value = self.value_inner(interp)?;
1155 self.last_span = (start, self.position);
1156 Ok(value)
1157 }
1158
1159 /// The source text of the value at `span`, when tracking is on.
1160 fn source_of(&self, span: (usize, usize)) -> Option<String> {
1161 if !self.track {
1162 return None;
1163 }
1164 self.text.get(span.0..span.1).map(str::to_string)
1165 }
1166
1167 fn value_inner(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
1168 match self.peek() {
1169 None => self.error("unexpected end of JSON input"),
1170 Some(b'{') => self.object(interp),
1171 Some(b'[') => self.array(interp),
1172 Some(b'"') => Ok(interp.string(self.string()?)),
1173 // A single-quoted string is only a value in the extended dialect.
1174 Some(b'\'') if self.ext => Ok(interp.string(self.string()?)),
1175 Some(b't') => self.literal("true", Value::Bool(true)),
1176 Some(b'f') => self.literal("false", Value::Bool(false)),
1177 Some(b'n') => self.literal("null", Value::Null),
1178 // The extended dialect starts a number at `.` (as in `.1`) and at `+`.
1179 Some(b'.') if self.ext => self.number(),
1180 Some(b'+') if self.ext => self.number(),
1181 Some(_) => self.number(),
1182 }
1183 }
1184
1185 fn literal(&mut self, word: &str, value: Value) -> Result<Value, JsonError> {
1186 if self.text[self.position..].starts_with(word) {
1187 self.position += word.len();
1188 Ok(value)
1189 } else {
1190 self.error("unexpected token")
1191 }
1192 }
1193
1194 fn number(&mut self) -> Result<Value, JsonError> {
1195 // RFC 8259 has a number start with `-` or a digit, and the scan below is happy to
1196 // take a leading `+` or `.` — which `f64::from_str` then accepts. Without this
1197 // guard `JSON.parse("+1")` and `JSON.parse(".1")` succeeded, which they must not.
1198 // The extended dialect allows both, so those two are gated on `ext`.
1199 // The extended dialect is checked by its own parser below: `Infinity` and `NaN`
1200 // start with letters, and `+` and `.` are legal there, so a first-character rule
1201 // would reject exactly the values it is meant to add.
1202 if !self.ext {
1203 match self.peek() {
1204 Some(b'-') | Some(b'0'..=b'9') => {}
1205 _ => return self.error("unexpected token in number"),
1206 }
1207 }
1208 let start = self.position;
1209 if matches!(self.peek(), Some(b'-')) || (self.ext && matches!(self.peek(), Some(b'+'))) {
1210 self.position += 1;
1211 }
1212 if self.ext {
1213 let negative = self.bytes.get(start) == Some(&b'-');
1214 // `Infinity` and `NaN` are only reachable after the sign has been consumed, so
1215 // `-Infinity` and `+NaN` fall out for free — same order as the reference.
1216 if self.rest().starts_with("Infinity") {
1217 self.position += "Infinity".len();
1218 return Ok(Value::Float(if negative {
1219 f64::NEG_INFINITY
1220 } else {
1221 f64::INFINITY
1222 }));
1223 }
1224 if self.rest().starts_with("NaN") {
1225 self.position += "NaN".len();
1226 // The sign does not survive: `-NaN` is still `NaN`, which is why the
1227 // reference's own test only checks `isNaN` for the signed forms.
1228 return Ok(Value::Float(f64::NAN));
1229 }
1230 // Radix prefixes. The reference accepts all three, though its comment only
1231 // mentions hexadecimal and octal.
1232 if self.bytes.get(self.position) == Some(&b'0') {
1233 let radix = match self.bytes.get(self.position + 1) {
1234 Some(b'x' | b'X') => Some(16u32),
1235 Some(b'o' | b'O') => Some(8),
1236 Some(b'b' | b'B') => Some(2),
1237 _ => None,
1238 };
1239 if let Some(radix) = radix {
1240 self.position += 2;
1241 let digits = self.position;
1242 while self
1243 .peek()
1244 .is_some_and(|byte| (byte as char).is_digit(radix))
1245 {
1246 self.position += 1;
1247 }
1248 if self.position == digits {
1249 return self.error("unexpected token in number");
1250 }
1251 let magnitude = u64::from_str_radix(&self.text[digits..self.position], radix)
1252 .map(|value| value as f64)
1253 .unwrap_or(f64::NAN);
1254 return Ok(Value::Float(if negative { -magnitude } else { magnitude }));
1255 }
1256 }
1257 }
1258 while let Some(byte) = self.peek() {
1259 match byte {
1260 b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-' => self.position += 1,
1261 _ => break,
1262 }
1263 }
1264 let text = &self.text[start..self.position];
1265 // The scan above is a *character-class* run, and `f64::from_str` is more permissive
1266 // than RFC 8259: it takes `01`, `1.` and `-01`, all of which the grammar rejects
1267 // (`int` is `0` or a nonzero digit followed by digits; `frac` needs a digit after the
1268 // point). Left unguarded, `JSON.parse("01")` answered `1` where the reference throws.
1269 //
1270 // Only in the strict dialect: the extended one is deliberately loose, and its own
1271 // callers (`std.parseExtJSON`) want `+1` and `.5`.
1272 if !self.ext && !is_rfc_number(text) {
1273 return self.error("invalid number");
1274 }
1275 text.parse::<f64>()
1276 .map(Value::Float)
1277 .map_err(|_| JsonError {
1278 message: "invalid number".to_string(),
1279 offset: start,
1280 })
1281 }
1282
1283 /// The text from the current position to the end.
1284 fn rest(&self) -> &str {
1285 &self.text[self.position.min(self.text.len())..]
1286 }
1287
1288 fn string(&mut self) -> Result<String, JsonError> {
1289 // The opening quote is already known to be there. `'` only reaches here in the
1290 // extended dialect; the callers check.
1291 let separator = self.peek().unwrap_or(b'"');
1292 self.position += 1;
1293 let mut out = String::new();
1294 loop {
1295 let Some(byte) = self.peek() else {
1296 return self.error("unterminated string");
1297 };
1298 match byte {
1299 _ if byte == separator => {
1300 self.position += 1;
1301 return Ok(out);
1302 }
1303 // A raw control character is not allowed in a JSON string: it has to be
1304 // escaped. Accepting one made `JSON.parse('"a<TAB>b"')` succeed where the
1305 // grammar requires a `SyntaxError`.
1306 0x00..=0x1F => {
1307 return self.error("control character in string");
1308 }
1309 b'\\' => {
1310 self.position += 1;
1311 let Some(escape) = self.peek() else {
1312 return self.error("unterminated escape");
1313 };
1314 self.position += 1;
1315 let start_of_escape = self.position - 1;
1316 match escape {
1317 // An escaped delimiter, and only the delimiter: `\"` inside a
1318 // single-quoted string is a bad escape in the reference too.
1319 b'"' if separator == b'"' => out.push('"'),
1320 b'\'' if separator == b'\'' => out.push('\''),
1321 b'\\' => out.push('\\'),
1322 b'/' => out.push('/'),
1323 b'b' => out.push('\u{8}'),
1324 b'f' => out.push('\u{c}'),
1325 b'n' => out.push('\n'),
1326 b'r' => out.push('\r'),
1327 b't' => out.push('\t'),
1328 // `\v` is not a JSON escape; the extended dialect adds it.
1329 b'v' if self.ext => out.push('\u{b}'),
1330 // A backslash before a newline continues the string on the next
1331 // line, dropping both characters. Only `\n`: `\r\n` is not
1332 // handled, matching `json_parse_string`.
1333 b'\n' if self.ext => {}
1334 b'u' => {
1335 let end = self.position + 4;
1336 if end > self.bytes.len() {
1337 return self.error("truncated \\u escape");
1338 }
1339 let hex = &self.text[self.position..end];
1340 let unit = u16::from_str_radix(hex, 16).map_err(|_| JsonError {
1341 message: "invalid \\u escape".to_string(),
1342 offset: start_of_escape,
1343 })?;
1344 self.position = end;
1345 // A surrogate pair arrives as two escapes; reassemble it.
1346 if (0xd800..0xdc00).contains(&unit)
1347 && self.text[self.position..].starts_with("\\u")
1348 {
1349 let tail_end = self.position + 6;
1350 if tail_end <= self.bytes.len() {
1351 let low = u16::from_str_radix(
1352 &self.text[self.position + 2..tail_end],
1353 16,
1354 )
1355 .unwrap_or(0);
1356 if (0xdc00..0xe000).contains(&low) {
1357 let combined = 0x10000
1358 + ((unit as u32 - 0xd800) << 10)
1359 + (low as u32 - 0xdc00);
1360 out.push(char::from_u32(combined).unwrap_or('\u{fffd}'));
1361 self.position = tail_end;
1362 continue;
1363 }
1364 }
1365 }
1366 out.push(char::from_u32(unit as u32).unwrap_or('\u{fffd}'));
1367 }
1368 // The offending character is the one just consumed, so the
1369 // position has to step back over it.
1370 other => {
1371 return Err(JsonError {
1372 message: format!("invalid escape \\{}", other as char),
1373 offset: self.position - 1,
1374 });
1375 }
1376 }
1377 }
1378 _ => {
1379 // Copy one whole UTF-8 character so multi-byte text survives.
1380 let rest = &self.text[self.position..];
1381 let character = rest.chars().next().ok_or_else(|| JsonError {
1382 message: "invalid UTF-8".to_string(),
1383 offset: self.position,
1384 })?;
1385 out.push(character);
1386 self.position += character.len_utf8();
1387 }
1388 }
1389 }
1390 }
1391
1392 /// A bare identifier used as a property key.
1393 ///
1394 /// The reference runs this through the full JS identifier tables, so it accepts non-ASCII
1395 /// letters. `is_alphanumeric` covers the same ground without pulling those tables into
1396 /// the JSON parser; an identifier the two disagree about would have to start with a
1397 /// non-ASCII, non-letter character, which no realistic config file does.
1398 fn identifier(&mut self) -> Result<String, JsonError> {
1399 let start = self.position;
1400 while self
1401 .text
1402 .get(start..)
1403 .and_then(|rest| rest.chars().next())
1404 .is_some_and(|_| self.position < self.text.len())
1405 {
1406 let character = self.text[self.position..]
1407 .chars()
1408 .next()
1409 .expect("the loop condition checked");
1410 let keep = if self.position == start {
1411 is_identifier_start(character as u32 as u8)
1412 || character.is_alphabetic()
1413 || character == '_'
1414 || character == '$'
1415 } else {
1416 character.is_alphanumeric() || character == '_' || character == '$'
1417 };
1418 if !keep {
1419 break;
1420 }
1421 self.position += character.len_utf8();
1422 }
1423 if self.position == start {
1424 return self.error("expected an identifier");
1425 }
1426 Ok(self.text[start..self.position].to_string())
1427 }
1428
1429 fn array(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
1430 self.position += 1;
1431 let mut elements = Vec::new();
1432 // `key -> source` for the primitive children only. An array or object child gets no
1433 // `source` at all, per `CreateJSONParseRecord`'s "if value is not an Object".
1434 let mut sources: Vec<String> = Vec::new();
1435 self.skip_whitespace();
1436 if matches!(self.peek(), Some(b']')) {
1437 self.position += 1;
1438 return Ok(Value::Object(interp.new_array(elements)));
1439 }
1440 loop {
1441 let value = self.value(interp)?;
1442 let source = if value.as_object().is_none() {
1443 self.source_of(self.last_span)
1444 } else {
1445 None
1446 };
1447 sources.push(source.unwrap_or_default());
1448 elements.push(value);
1449 self.skip_whitespace();
1450 match self.peek() {
1451 Some(b',') => {
1452 self.position += 1;
1453 // A trailing comma closes the array in the extended dialect.
1454 self.skip_whitespace();
1455 if self.ext && matches!(self.peek(), Some(b']')) {
1456 self.position += 1;
1457 return Ok(self.finish_array(interp, elements, sources));
1458 }
1459 }
1460 Some(b']') => {
1461 self.position += 1;
1462 return Ok(self.finish_array(interp, elements, sources));
1463 }
1464 _ => return self.error("expected ',' or ']'"),
1465 }
1466 }
1467 }
1468
1469 /// Attach the `key -> source` table to a parsed array, under a hidden slot.
1470 ///
1471 /// A slot rather than a visible property: `Object.keys`/`JSON.stringify`/`for...in` must
1472 /// not see it, and `assertOnlyOwnProperties` in the test suite checks exactly that the
1473 /// parsed objects have no extra own properties.
1474 fn finish_array(
1475 &self,
1476 interp: &mut Interp<'_>,
1477 elements: Vec<Value>,
1478 sources: Vec<String>,
1479 ) -> Value {
1480 let array = interp.new_array(elements);
1481 if sources.iter().any(|source| !source.is_empty()) {
1482 let table = interp.new_object(None);
1483 for (index, source) in sources.into_iter().enumerate() {
1484 if !source.is_empty() {
1485 table.define_data(&index.to_string(), interp.string(source));
1486 }
1487 }
1488 interp.internal_set(&array, "_json_source", Value::Object(table));
1489 }
1490 Value::Object(array)
1491 }
1492
1493 /// [`Parser::finish_array`] for objects, whose keys may be arbitrary strings.
1494 fn attach_sources(
1495 &self,
1496 interp: &mut Interp<'_>,
1497 object: &Gc<JsObject>,
1498 sources: Vec<(String, String)>,
1499 ) {
1500 if sources.is_empty() {
1501 return;
1502 }
1503 let table = interp.new_object(None);
1504 for (key, source) in sources {
1505 table.define_data(&key, interp.string(source));
1506 }
1507 interp.internal_set(object, "_json_source", Value::Object(table));
1508 }
1509
1510 fn object(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
1511 self.position += 1;
1512 let proto = interp.realm.object_proto.clone();
1513 let object = interp.new_object(Some(proto));
1514 let mut sources: Vec<(String, String)> = Vec::new();
1515 self.skip_whitespace();
1516 if matches!(self.peek(), Some(b'}')) {
1517 self.position += 1;
1518 return Ok(Value::Object(object));
1519 }
1520 loop {
1521 self.skip_whitespace();
1522 let key = match self.peek() {
1523 Some(b'"') => self.string()?,
1524 // A bare identifier as a key, e.g. `{ z2: null }`.
1525 Some(b'\'') if self.ext => self.string()?,
1526 Some(byte) if self.ext && is_identifier_start(byte) => self.identifier()?,
1527 _ => return self.error("expecting property name"),
1528 };
1529 self.skip_whitespace();
1530 if !matches!(self.peek(), Some(b':')) {
1531 return self.error("expected ':'");
1532 }
1533 self.position += 1;
1534 let value = self.value(interp)?;
1535 if value.as_object().is_none()
1536 && let Some(source) = self.source_of(self.last_span)
1537 {
1538 sources.push((key.clone(), source));
1539 }
1540 object.define_data(&key, value);
1541 self.skip_whitespace();
1542 match self.peek() {
1543 Some(b',') => {
1544 self.position += 1;
1545 // A trailing comma closes the object in the extended dialect.
1546 self.skip_whitespace();
1547 if self.ext && matches!(self.peek(), Some(b'}')) {
1548 self.position += 1;
1549 self.attach_sources(interp, &object, sources);
1550 return Ok(Value::Object(object));
1551 }
1552 }
1553 Some(b'}') => {
1554 self.position += 1;
1555 self.attach_sources(interp, &object, sources);
1556 return Ok(Value::Object(object));
1557 }
1558 _ => return self.error("expected ',' or '}'"),
1559 }
1560 }
1561 }
1562}