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