Skip to main content

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