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    let global = interp.realm.global.clone();
27    global.define(
28        "JSON",
29        Property::with_attributes(Value::Object(json), true, false),
30    );
31}
32
33// ---------------------------------------------------------------------------
34// stringify
35// ---------------------------------------------------------------------------
36
37fn stringify(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
38    let value = arg(args, 0);
39    // The second argument restricts or rewrites what is serialised: a function is called for
40    // every key, an array is the list of keys that survive. Ignoring it made
41    // `JSON.stringify({a:1,b:2}, ["a"])` emit both keys.
42    let replacer = Replacer::new(interp, &arg(args, 1))?;
43    // The indent argument may be a number of spaces or a string used verbatim.
44    let indent = match arg(args, 2) {
45        Value::Int(_) | Value::Float(_) => {
46            let count = arg(args, 2).to_number().clamp(0.0, 10.0) as usize;
47            " ".repeat(count)
48        }
49        Value::String(text) => text.to_string_lossy().chars().take(10).collect(),
50        _ => String::new(),
51    };
52    let mut out = String::new();
53    let root = make_root_holder(interp, &value)?;
54    match write_value(
55        interp,
56        &mut Writer {
57            out: &mut out,
58            indent: &indent,
59            depth: 0,
60        },
61        &root,
62        &value,
63        "",
64        &replacer,
65    )? {
66        // `undefined`, a function and a symbol serialise to nothing at the top level.
67        true => Ok(interp.string(out)),
68        false => Ok(Value::Undefined),
69    }
70}
71
72/// The `{"": value}` wrapper the spec puts around the root value.
73///
74/// A replacer function is called with this as `this` for the root, and `this[""]` is the
75/// value — which is how a replacer that recurses through `this` gets its starting point.
76fn make_root_holder(interp: &mut Interp<'_>, value: &Value) -> JsResult<Value> {
77    let holder = interp.new_object(None);
78    interp.set_property(&holder, "", value.clone())?;
79    Ok(Value::Object(holder))
80}
81
82/// `JSON.stringify`'s `replacer` argument.
83///
84/// A function is called with the holder and the key; an array names the properties to keep.
85/// Anything else (including `undefined`) is the identity.
86enum Replacer {
87    None,
88    /// The function to call, and the raw value to pass as `this` (the holder).
89    Function(Value),
90    /// The keys to keep, in the order first seen.
91    Keys(Vec<String>),
92}
93
94impl Replacer {
95    fn new(interp: &mut Interp<'_>, value: &Value) -> JsResult<Replacer> {
96        let Value::Object(object) = value else {
97            return Ok(Replacer::None);
98        };
99        if object.is_callable() {
100            return Ok(Replacer::Function(value.clone()));
101        }
102        if !object.is_array() {
103            return Ok(Replacer::None);
104        }
105        // `SerializeJSONProperty`'s step 3: every element is coerced, and only a string or
106        // number contributes a key. A repeated key keeps its first position.
107        let length = object.array_length().unwrap_or(0);
108        let mut keys: Vec<String> = Vec::new();
109        for index in 0..length {
110            let element = interp.get_property(object, &format!("{index}"))?;
111            let Some(element) = element else {
112                continue;
113            };
114            let text = match &element {
115                Value::String(text) => text.to_string_lossy().to_string(),
116                Value::Int(_) | Value::Float(_) => number_to_string(element.to_number()),
117                _ => continue,
118            };
119            if !keys.contains(&text) {
120                keys.push(text);
121            }
122        }
123        Ok(Replacer::Keys(keys))
124    }
125
126    /// Whether `key` may be serialised. Only the array form filters; a function is applied
127    /// to the value instead, in [`Replacer::apply`].
128    fn keeps(&self, key: &str) -> bool {
129        match self {
130            // The root is always visited.
131            Replacer::Keys(keys) => key.is_empty() || keys.iter().any(|k| k == key),
132            Replacer::None | Replacer::Function(_) => true,
133        }
134    }
135
136    /// `SerializeJSONProperty`'s replacer step: the function replaces the value.
137    fn apply(
138        &self,
139        interp: &mut Interp<'_>,
140        holder: &Value,
141        value: &Value,
142        key: &str,
143    ) -> JsResult<Value> {
144        let Replacer::Function(function) = self else {
145            return Ok(value.clone());
146        };
147        interp.call_value(
148            function.clone(),
149            holder.clone(),
150            vec![interp.string(key), value.clone()],
151        )
152    }
153}
154
155/// Serialise `value` into `out`. Returns whether anything was written, which is how
156/// a top-level `undefined` becomes the value `undefined` rather than `"undefined"`.
157///
158/// `key` is the property name the value was read from, which `toJSON` receives; the
159/// root value is passed the empty string, as the spec's wrapper object does.
160/// The primitive inside a wrapper object, or the value unchanged.
161///
162/// `_value` is the slot this engine's `new Number(x)` and `Object(x)` fill in, so it is
163/// the same thing the spec's internal slots carry.
164fn unwrap_primitive_wrapper(interp: &Interp<'_>, value: &Value) -> Value {
165    let Some(object) = value.as_object() else {
166        return value.clone();
167    };
168    let Some(inner) = interp.internal_get(object, "_value") else {
169        return value.clone();
170    };
171    // Only a box of a *primitive*: an ordinary object that happens to have `_value` must
172    // keep serialising as an object.
173    match inner {
174        Value::Int(_) | Value::Float(_) | Value::String(_) | Value::Bool(_) | Value::BigInt(_) => {
175            inner
176        }
177        _ => value.clone(),
178    }
179}
180
181/// Where the text is being written: the buffer, the indent unit and how deep the current
182/// value sits. Grouped so `write_value` keeps a readable argument list.
183struct Writer<'a> {
184    out: &'a mut String,
185    indent: &'a str,
186    depth: usize,
187}
188
189fn write_value(
190    interp: &mut Interp<'_>,
191    writer: &mut Writer<'_>,
192    holder: &Value,
193    value: &Value,
194    key: &str,
195    replacer: &Replacer,
196) -> JsResult<bool> {
197    let Writer { out, indent, depth } = writer;
198    let (out, indent, depth) = (out, *indent, *depth);
199    // The array form filters by key before anything else looks at the value.
200    if !replacer.keeps(key) {
201        return Ok(false);
202    }
203    // A value carrying a `toJSON` method is replaced by whatever that returns, and
204    // the replacement is not asked for `toJSON` again. This is how a `Date`
205    // serialises to its ISO string.
206    let value = &call_to_json(interp, value, key)?;
207    // A replacer *function* receives the value after `toJSON` and may replace it outright.
208    // `this` is the holder — the object or array the value was read from — because a
209    // replacer commonly reads sibling properties through `this[key]`.
210    let value = &replacer.apply(interp, holder, value, key)?;
211    // A wrapper object serialises as the primitive it wraps: `JSON.stringify(Object(1))`
212    // is `"1"`, not `"{}"`. SerialiseJSONProperty unwraps `[[NumberData]]`,
213    // `[[StringData]]`, `[[BooleanData]]` and `[[BigIntData]]` before looking at the
214    // object's enumerable keys, and a wrapper has none of its own — which is why skipping
215    // the step printed an empty object.
216    let value = &unwrap_primitive_wrapper(interp, value);
217    match value {
218        // A symbol serialises to nothing, exactly like `undefined`: `JSON.stringify`
219        // drops it from an object and answers `undefined` for it at the top level.
220        // A bigint has no JSON form, and the spec makes that an error rather than a
221        // silent omission — losing a number is not the same as losing `undefined`.
222        Value::BigInt(_) => Err(interp.type_error("BigInt value can't be serialized in JSON")),
223        Value::Undefined
224        | Value::Symbol(_)
225        | Value::Uninitialized
226        | Value::Hole
227        | Value::CatchOffset(_)
228        | Value::ReturnAddress(_) => Ok(false),
229        Value::Null => {
230            out.push_str("null");
231            Ok(true)
232        }
233        Value::Bool(value) => {
234            out.push_str(if *value { "true" } else { "false" });
235            Ok(true)
236        }
237        Value::Int(_) | Value::Float(_) => {
238            let number = value.to_number();
239            // `NaN` and the infinities serialise as `null`.
240            if number.is_finite() {
241                out.push_str(&number_to_string(number));
242            } else {
243                out.push_str("null");
244            }
245            Ok(true)
246        }
247        Value::String(text) => {
248            write_string(text.wtf8(), out);
249            Ok(true)
250        }
251        Value::Object(object) => {
252            if object.is_callable() {
253                return Ok(false);
254            }
255            if object.is_array() {
256                write_array(interp, &mut Writer { out, indent, depth }, object, replacer)?;
257            } else {
258                write_object(interp, &mut Writer { out, indent, depth }, object, replacer)?;
259            }
260            Ok(true)
261        }
262    }
263}
264
265/// `SerializeJSONProperty`'s `toJSON` step, applied once.
266fn call_to_json(interp: &mut Interp<'_>, value: &Value, key: &str) -> JsResult<Value> {
267    let Value::Object(object) = value else {
268        return Ok(value.clone());
269    };
270    let Some(method) = interp.get_property(object, "toJSON")? else {
271        return Ok(value.clone());
272    };
273    if !matches!(&method, Value::Object(function) if function.is_callable()) {
274        return Ok(value.clone());
275    }
276    interp.call_value(method, value.clone(), vec![interp.string(key)])
277}
278
279fn write_array(
280    interp: &mut Interp<'_>,
281    writer: &mut Writer<'_>,
282    array: &Gc<JsObject>,
283    replacer: &Replacer,
284) -> JsResult<()> {
285    let Writer { out, indent, depth } = writer;
286    let (out, indent, depth) = (out, *indent, *depth);
287    let length = array.array_length().unwrap_or(0);
288    if length == 0 {
289        out.push_str("[]");
290        return Ok(());
291    }
292    out.push('[');
293    for index in 0..length {
294        if index > 0 {
295            out.push(',');
296        }
297        newline(out, indent, depth + 1);
298        // `[[Get]]`, not the element vector: an accessor defined on an index lives in the
299        // property table and the slot it shadows is a hole, so reading the vector directly
300        // printed `null` for `Object.defineProperty(a, "0", {get})`.
301        let element = match array.array_get(index) {
302            Some(Value::Hole) | None => interp
303                .get_property_key(array, &PropertyKey::from(index.to_string()))?
304                .unwrap_or(Value::Undefined),
305            Some(value) => value,
306        };
307        // A hole or an unserialisable element becomes `null`, because an array's
308        // positions are part of its meaning.
309        if !write_value(
310            interp,
311            &mut Writer {
312                out,
313                indent,
314                depth: depth + 1,
315            },
316            &Value::Object(array.clone()),
317            &element,
318            &index.to_string(),
319            replacer,
320        )? {
321            out.push_str("null");
322        }
323    }
324    newline(out, indent, depth);
325    out.push(']');
326    Ok(())
327}
328
329fn write_object(
330    interp: &mut Interp<'_>,
331    writer: &mut Writer<'_>,
332    object: &Gc<JsObject>,
333    replacer: &Replacer,
334) -> JsResult<()> {
335    let Writer { out, indent, depth } = writer;
336    let (out, indent, depth) = (out, *indent, *depth);
337    // Enumerable own keys in the spec's order, skipping keys whose values do not
338    // serialise (a function-valued property is omitted, not `null`).
339    //
340    // Through `[[OwnPropertyKeys]]` and `[[GetOwnProperty]]`, so a proxy serialises as
341    // its handler describes it: reading the property table directly made
342    // `JSON.stringify(proxy)` emit `{}` for every proxy.
343    let mut keys: Vec<crate::object::PropertyKey> = Vec::new();
344    for key in interp.object_own_property_keys(object)? {
345        if key.is_symbol() {
346            // A symbol-keyed property is invisible to `JSON.stringify`.
347            continue;
348        }
349        let enumerable = interp
350            .object_get_own_property(object, &key)?
351            .is_some_and(|property| property.enumerable);
352        if enumerable {
353            keys.push(key);
354        }
355    }
356    let mut written = 0usize;
357    let mut body = String::new();
358    for key in keys {
359        // Two views of the same key: the replacer's plumbing takes a `&str` (it compares
360        // against the replacer array and hands the key to a user function), while the
361        // emitted JSON must keep the key's own code units — a key may hold an unpaired
362        // surrogate, and flattening it here would print a different property name.
363        let key_text = key.as_str().unwrap_or_default().to_string();
364        let key_json = key.as_wtf8().cloned().unwrap_or_default();
365        let Some(value) = interp.get_property_key(object, &key)? else {
366            continue;
367        };
368        let mut piece = String::new();
369        // Render the value first so an unrepresentable one can be skipped whole.
370        if !write_value(
371            interp,
372            &mut Writer {
373                out: &mut piece,
374                indent,
375                depth: depth + 1,
376            },
377            &Value::Object(object.clone()),
378            &value,
379            &key_text,
380            replacer,
381        )? {
382            continue;
383        }
384        if written > 0 {
385            body.push(',');
386        }
387        newline(&mut body, indent, depth + 1);
388        let mut escaped = String::new();
389        write_string(&key_json, &mut escaped);
390        body.push_str(&escaped);
391        body.push(':');
392        if !indent.is_empty() {
393            body.push(' ');
394        }
395        body.push_str(&piece);
396        written += 1;
397    }
398    if written == 0 {
399        out.push_str("{}");
400        return Ok(());
401    }
402    out.push('{');
403    out.push_str(&body);
404    newline(out, indent, depth);
405    out.push('}');
406    Ok(())
407}
408
409/// Emit the indentation for one level, or nothing when not pretty-printing.
410fn newline(out: &mut String, indent: &str, depth: usize) {
411    if indent.is_empty() {
412        return;
413    }
414    out.push('\n');
415    for _ in 0..depth {
416        out.push_str(indent);
417    }
418}
419
420/// Write `text` as a JSON string literal.
421///
422/// The escapes are the spec's twenty-odd: the two mandatory ones, the two that are
423/// required for well-formed JSON in a script (`\u2028`/`\u2029`), and control
424/// characters below `0x20` as `\u00XX`.
425fn write_string(text: &crate::value::Wtf8, out: &mut String) {
426    out.push('"');
427    // Code *units*, because a string may hold an unpaired surrogate and JSON requires one
428    // to be written as `\udXXX` rather than dropped or replaced by U+FFFD. A valid pair is
429    // folded back into its astral character, which is what the reference prints and what
430    // keeps well-formed text readable in the output.
431    let units = text.to_units();
432    let mut index = 0;
433    while index < units.len() {
434        let unit = units[index];
435        if (0xD800..0xDC00).contains(&unit)
436            && let Some(&low) = units.get(index + 1)
437            && (0xDC00..0xE000).contains(&low)
438        {
439            let code = 0x10000 + ((u32::from(unit) - 0xD800) << 10) + (u32::from(low) - 0xDC00);
440            write_char(char::from_u32(code).unwrap_or('\u{fffd}'), out);
441            index += 2;
442            continue;
443        }
444        if (0xD800..0xE000).contains(&unit) {
445            out.push_str(&format!("\\u{unit:04x}"));
446            index += 1;
447            continue;
448        }
449        write_char(char::from_u32(u32::from(unit)).unwrap_or('\u{fffd}'), out);
450        index += 1;
451    }
452    out.push('"');
453}
454
455/// One non-surrogate code unit's escape.
456fn write_char(character: char, out: &mut String) {
457    match character {
458        '"' => out.push_str("\\\""),
459        '\\' => out.push_str("\\\\"),
460        '\n' => out.push_str("\\n"),
461        '\r' => out.push_str("\\r"),
462        '\t' => out.push_str("\\t"),
463        '\u{8}' => out.push_str("\\b"),
464        '\u{c}' => out.push_str("\\f"),
465        c if (c as u32) < 0x20 => {
466            out.push_str(&format!("\\u{:04x}", c as u32));
467        }
468        c => out.push(c),
469    }
470}
471
472// ---------------------------------------------------------------------------
473// parse
474// ---------------------------------------------------------------------------
475
476/// Parse `text`, either as RFC 8259 JSON or in the extended dialect.
477///
478/// The extended dialect is what the reference calls `JS_PARSE_JSON_EXT`: the same parser
479/// with a flag, not a separate parser and not a pre-processing pass. It is exposed to
480/// scripts only through `std.parseExtJSON`, so `JSON.parse` stays strict.
481pub fn parse_text(interp: &mut Interp<'_>, text: &str, ext: bool) -> JsResult<Value> {
482    let mut parser = Parser {
483        bytes: text.as_bytes(),
484        text,
485        position: 0,
486        ext,
487    };
488    parser.skip_whitespace();
489    let value = match parser.value(interp) {
490        Ok(value) => value,
491        Err(error) => {
492            return Err(crate::interp::Signal::Throw(json_error(
493                interp, text, error,
494            )));
495        }
496    };
497    parser.skip_whitespace();
498    if parser.position != parser.bytes.len() {
499        return Err(crate::interp::Signal::Throw(json_error(
500            interp,
501            text,
502            JsonError {
503                message: "unexpected data after JSON value".to_string(),
504                offset: parser.position,
505            },
506        )));
507    }
508    Ok(value)
509}
510
511fn parse(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
512    let text = arg(args, 0).to_js_string();
513    let value = parse_text(interp, &text, false)?;
514    // The second argument rewrites the parsed tree bottom-up. Ignoring it made
515    // `JSON.parse('{"a":1}', (k, v) => v * 2).a` answer `1`.
516    let reviver = arg(args, 1);
517    let is_reviver = matches!(&reviver, Value::Object(function) if function.is_callable());
518    if !is_reviver {
519        return Ok(value);
520    }
521    // `InternalizeJSONProperty` starts from `{"": value}`, so the root is visited last and
522    // may itself be replaced.
523    let root = make_root_holder(interp, &value)?;
524    let Value::Object(root) = &root else {
525        return Ok(value);
526    };
527    internalize_json_property(interp, root, "", &reviver)
528}
529
530/// `CreateDataProperty`, which differs from `Set` in exactly the case a reviver hits: an
531/// existing non-configurable property keeps its value instead of being overwritten, and the
532/// refusal is not an error.
533fn create_data_property(
534    interp: &mut Interp<'_>,
535    object: &Gc<JsObject>,
536    key: &str,
537    value: Value,
538) -> JsResult<()> {
539    let key = crate::object::PropertyKey::from(key);
540    // A property that already exists and cannot be redefined keeps its old value: the
541    // definition is refused rather than applied. `Object.defineProperty` would report that
542    // refusal through its return value, but here a reviver that froze a property while
543    // visiting an earlier key must simply see it stay frozen.
544    if interp
545        .object_get_own_property(object, &key)?
546        .is_some_and(|existing| !existing.configurable)
547    {
548        return Ok(());
549    }
550    let property = crate::object::Property {
551        value: Some(value),
552        writable: true,
553        enumerable: true,
554        configurable: true,
555        ..crate::object::Property::default()
556    };
557    interp.object_define_own_property(object, &key, property)?;
558    Ok(())
559}
560
561/// `InternalizeJSONProperty`: call the reviver on every property, depth first, and drop the
562/// ones it answers `undefined` for.
563fn internalize_json_property(
564    interp: &mut Interp<'_>,
565    holder: &Gc<JsObject>,
566    key: &str,
567    reviver: &Value,
568) -> JsResult<Value> {
569    let Some(value) = interp.get_property(holder, key)? else {
570        return Ok(Value::Undefined);
571    };
572    // Arrays are walked by index and objects by their enumerable own keys; a primitive has
573    // nothing to walk, so it goes straight to the call.
574    if let Value::Object(object) = &value {
575        if object.is_array() {
576            let length = object.array_length().unwrap_or(0);
577            for index in 0..length {
578                let element_key = index.to_string();
579                let replaced = internalize_json_property(interp, object, &element_key, reviver)?;
580                if matches!(replaced, Value::Undefined) {
581                    interp.delete_property(object, &element_key)?;
582                } else {
583                    // `CreateDataProperty`, not `Set`: when the property already exists and
584                    // refuses redefinition the new value is dropped. A reviver that froze a
585                    // property while visiting an earlier key must not have it overwritten by
586                    // a later branch.
587                    create_data_property(interp, object, &element_key, replaced)?;
588                }
589            }
590        } else {
591            for name in interp.object_own_property_keys(object)? {
592                let Some(name) = name.as_str() else {
593                    continue;
594                };
595                let name = name.to_string();
596                let replaced = internalize_json_property(interp, object, &name, reviver)?;
597                if matches!(replaced, Value::Undefined) {
598                    interp.delete_property(object, &name)?;
599                } else {
600                    create_data_property(interp, object, &name, replaced)?;
601                }
602            }
603        }
604    }
605    interp.call_value(
606        reviver.clone(),
607        Value::Object(holder.clone()),
608        vec![interp.string(key), value],
609    )
610}
611
612/// A `SyntaxError` that reports where in the JSON text parsing failed.
613///
614/// The reference builds these with an explicit position, so the trace starts with
615/// `    at <input>:line:column` — the position inside the text — and only then lists
616/// the caller. `<input>` is the reference's placeholder for text that came from a
617/// string rather than a file, so it is kept even when the caller is a real script.
618fn json_error(interp: &mut Interp<'_>, text: &str, error: JsonError) -> Value {
619    let (line, column) = line_and_column(text, error.offset);
620    let trace = format!("    at <input>:{line}:{column}\n{}", interp.stack_trace());
621    let value = interp.make_error("SyntaxError", &error.message);
622    if let Value::Object(object) = &value {
623        let text = interp.string(trace);
624        object.define(
625            "stack",
626            crate::object::Property::with_attributes(text, true, true),
627        );
628    }
629    value
630}
631
632/// The 1-based line and column of `offset` in `text`.
633///
634/// Columns count UTF-16 code units, like every other position in this engine, so a
635/// character outside the BMP counts twice.
636fn line_and_column(text: &str, offset: usize) -> (usize, usize) {
637    let before = &text[..offset.min(text.len())];
638    let line = before.matches('\n').count() + 1;
639    let line_start = before.rfind('\n').map_or(0, |index| index + 1);
640    let column = before[line_start..].encode_utf16().count() + 1;
641    (line, column)
642}
643
644/// A JSON syntax error and where in the JSON text it happened.
645///
646/// The offset is what lets `JSON.parse` report a position the way the reference does:
647/// its stack starts with the line and column inside the *text being parsed*, not with
648/// the caller's frame.
649struct JsonError {
650    message: String,
651    offset: usize,
652}
653
654struct Parser<'a> {
655    bytes: &'a [u8],
656    text: &'a str,
657    position: usize,
658    /// Whether the extended dialect is in force. Every relaxation below is gated on it, so
659    /// `JSON.parse` keeps rejecting what RFC 8259 rejects.
660    ext: bool,
661}
662
663/// Whether `byte` may start a bare identifier key: the reference's `TOK_IDENT` start set.
664fn is_identifier_start(byte: u8) -> bool {
665    byte.is_ascii_alphabetic() || byte == b'_' || byte == b'$'
666}
667
668impl Parser<'_> {
669    /// An error blamed on the parser's current position.
670    fn error<T>(&self, message: impl Into<String>) -> Result<T, JsonError> {
671        Err(JsonError {
672            message: message.into(),
673            offset: self.position,
674        })
675    }
676
677    fn skip_whitespace(&mut self) {
678        loop {
679            while let Some(byte) = self.bytes.get(self.position) {
680                match byte {
681                    b' ' | b'\t' | b'\n' | b'\r' => self.position += 1,
682                    // `JSONWhitespace` does not match <VT> or <FF>; the extended dialect
683                    // does, so `formfeed` and `vertical tab` count as space there.
684                    b'\x0b' | b'\x0c' if self.ext => self.position += 1,
685                    _ => break,
686                }
687            }
688            // Comments are whitespace in the extended dialect, and they may abut each other,
689            // so this is a loop rather than one check.
690            if !self.ext || !self.skip_one_comment() {
691                return;
692            }
693        }
694    }
695
696    /// Skip one `/* … */` or `// …` comment, reporting whether there was one.
697    ///
698    /// An unterminated block comment leaves the position at the end, so the caller reports
699    /// "unexpected end of JSON input" instead of silently accepting a truncated document.
700    fn skip_one_comment(&mut self) -> bool {
701        if self.bytes.get(self.position) != Some(&b'/') {
702            return false;
703        }
704        match self.bytes.get(self.position + 1) {
705            Some(b'*') => {
706                self.position += 2;
707                while self.position < self.bytes.len() {
708                    if self.bytes[self.position..].starts_with(b"*/") {
709                        self.position += 2;
710                        return true;
711                    }
712                    self.position += 1;
713                }
714                true
715            }
716            Some(b'/') => {
717                self.position += 2;
718                // A line comment ends at CR, LF, or a Unicode line separator.
719                while let Some(character) = self.text[self.position..].chars().next() {
720                    if matches!(character, '\r' | '\n' | '\u{2028}' | '\u{2029}') {
721                        break;
722                    }
723                    self.position += character.len_utf8();
724                }
725                true
726            }
727            _ => false,
728        }
729    }
730
731    fn peek(&self) -> Option<u8> {
732        self.bytes.get(self.position).copied()
733    }
734
735    fn value(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
736        self.skip_whitespace();
737        match self.peek() {
738            None => self.error("unexpected end of JSON input"),
739            Some(b'{') => self.object(interp),
740            Some(b'[') => self.array(interp),
741            Some(b'"') => Ok(interp.string(self.string()?)),
742            // A single-quoted string is only a value in the extended dialect.
743            Some(b'\'') if self.ext => Ok(interp.string(self.string()?)),
744            Some(b't') => self.literal("true", Value::Bool(true)),
745            Some(b'f') => self.literal("false", Value::Bool(false)),
746            Some(b'n') => self.literal("null", Value::Null),
747            // The extended dialect starts a number at `.` (as in `.1`) and at `+`.
748            Some(b'.') if self.ext => self.number(),
749            Some(b'+') if self.ext => self.number(),
750            Some(_) => self.number(),
751        }
752    }
753
754    fn literal(&mut self, word: &str, value: Value) -> Result<Value, JsonError> {
755        if self.text[self.position..].starts_with(word) {
756            self.position += word.len();
757            Ok(value)
758        } else {
759            self.error("unexpected token")
760        }
761    }
762
763    fn number(&mut self) -> Result<Value, JsonError> {
764        // RFC 8259 has a number start with `-` or a digit, and the scan below is happy to
765        // take a leading `+` or `.` — which `f64::from_str` then accepts. Without this
766        // guard `JSON.parse("+1")` and `JSON.parse(".1")` succeeded, which they must not.
767        // The extended dialect allows both, so those two are gated on `ext`.
768        // The extended dialect is checked by its own parser below: `Infinity` and `NaN`
769        // start with letters, and `+` and `.` are legal there, so a first-character rule
770        // would reject exactly the values it is meant to add.
771        if !self.ext {
772            match self.peek() {
773                Some(b'-') | Some(b'0'..=b'9') => {}
774                _ => return self.error("unexpected token in number"),
775            }
776        }
777        let start = self.position;
778        if matches!(self.peek(), Some(b'-')) || (self.ext && matches!(self.peek(), Some(b'+'))) {
779            self.position += 1;
780        }
781        if self.ext {
782            let negative = self.bytes.get(start) == Some(&b'-');
783            // `Infinity` and `NaN` are only reachable after the sign has been consumed, so
784            // `-Infinity` and `+NaN` fall out for free — same order as the reference.
785            if self.rest().starts_with("Infinity") {
786                self.position += "Infinity".len();
787                return Ok(Value::Float(if negative {
788                    f64::NEG_INFINITY
789                } else {
790                    f64::INFINITY
791                }));
792            }
793            if self.rest().starts_with("NaN") {
794                self.position += "NaN".len();
795                // The sign does not survive: `-NaN` is still `NaN`, which is why the
796                // reference's own test only checks `isNaN` for the signed forms.
797                return Ok(Value::Float(f64::NAN));
798            }
799            // Radix prefixes. The reference accepts all three, though its comment only
800            // mentions hexadecimal and octal.
801            if self.bytes.get(self.position) == Some(&b'0') {
802                let radix = match self.bytes.get(self.position + 1) {
803                    Some(b'x' | b'X') => Some(16u32),
804                    Some(b'o' | b'O') => Some(8),
805                    Some(b'b' | b'B') => Some(2),
806                    _ => None,
807                };
808                if let Some(radix) = radix {
809                    self.position += 2;
810                    let digits = self.position;
811                    while self
812                        .peek()
813                        .is_some_and(|byte| (byte as char).is_digit(radix))
814                    {
815                        self.position += 1;
816                    }
817                    if self.position == digits {
818                        return self.error("unexpected token in number");
819                    }
820                    let magnitude = u64::from_str_radix(&self.text[digits..self.position], radix)
821                        .map(|value| value as f64)
822                        .unwrap_or(f64::NAN);
823                    return Ok(Value::Float(if negative { -magnitude } else { magnitude }));
824                }
825            }
826        }
827        while let Some(byte) = self.peek() {
828            match byte {
829                b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-' => self.position += 1,
830                _ => break,
831            }
832        }
833        let text = &self.text[start..self.position];
834        text.parse::<f64>()
835            .map(Value::Float)
836            .map_err(|_| JsonError {
837                message: "invalid number".to_string(),
838                offset: start,
839            })
840    }
841
842    /// The text from the current position to the end.
843    fn rest(&self) -> &str {
844        &self.text[self.position.min(self.text.len())..]
845    }
846
847    fn string(&mut self) -> Result<String, JsonError> {
848        // The opening quote is already known to be there. `'` only reaches here in the
849        // extended dialect; the callers check.
850        let separator = self.peek().unwrap_or(b'"');
851        self.position += 1;
852        let mut out = String::new();
853        loop {
854            let Some(byte) = self.peek() else {
855                return self.error("unterminated string");
856            };
857            match byte {
858                _ if byte == separator => {
859                    self.position += 1;
860                    return Ok(out);
861                }
862                // A raw control character is not allowed in a JSON string: it has to be
863                // escaped. Accepting one made `JSON.parse('"a<TAB>b"')` succeed where the
864                // grammar requires a `SyntaxError`.
865                0x00..=0x1F => {
866                    return self.error("control character in string");
867                }
868                b'\\' => {
869                    self.position += 1;
870                    let Some(escape) = self.peek() else {
871                        return self.error("unterminated escape");
872                    };
873                    self.position += 1;
874                    let start_of_escape = self.position - 1;
875                    match escape {
876                        // An escaped delimiter, and only the delimiter: `\"` inside a
877                        // single-quoted string is a bad escape in the reference too.
878                        b'"' if separator == b'"' => out.push('"'),
879                        b'\'' if separator == b'\'' => out.push('\''),
880                        b'\\' => out.push('\\'),
881                        b'/' => out.push('/'),
882                        b'b' => out.push('\u{8}'),
883                        b'f' => out.push('\u{c}'),
884                        b'n' => out.push('\n'),
885                        b'r' => out.push('\r'),
886                        b't' => out.push('\t'),
887                        // `\v` is not a JSON escape; the extended dialect adds it.
888                        b'v' if self.ext => out.push('\u{b}'),
889                        // A backslash before a newline continues the string on the next
890                        // line, dropping both characters. Only `\n`: `\r\n` is not
891                        // handled, matching `json_parse_string`.
892                        b'\n' if self.ext => {}
893                        b'u' => {
894                            let end = self.position + 4;
895                            if end > self.bytes.len() {
896                                return self.error("truncated \\u escape");
897                            }
898                            let hex = &self.text[self.position..end];
899                            let unit = u16::from_str_radix(hex, 16).map_err(|_| JsonError {
900                                message: "invalid \\u escape".to_string(),
901                                offset: start_of_escape,
902                            })?;
903                            self.position = end;
904                            // A surrogate pair arrives as two escapes; reassemble it.
905                            if (0xd800..0xdc00).contains(&unit)
906                                && self.text[self.position..].starts_with("\\u")
907                            {
908                                let tail_end = self.position + 6;
909                                if tail_end <= self.bytes.len() {
910                                    let low = u16::from_str_radix(
911                                        &self.text[self.position + 2..tail_end],
912                                        16,
913                                    )
914                                    .unwrap_or(0);
915                                    if (0xdc00..0xe000).contains(&low) {
916                                        let combined = 0x10000
917                                            + ((unit as u32 - 0xd800) << 10)
918                                            + (low as u32 - 0xdc00);
919                                        out.push(char::from_u32(combined).unwrap_or('\u{fffd}'));
920                                        self.position = tail_end;
921                                        continue;
922                                    }
923                                }
924                            }
925                            out.push(char::from_u32(unit as u32).unwrap_or('\u{fffd}'));
926                        }
927                        // The offending character is the one just consumed, so the
928                        // position has to step back over it.
929                        other => {
930                            return Err(JsonError {
931                                message: format!("invalid escape \\{}", other as char),
932                                offset: self.position - 1,
933                            });
934                        }
935                    }
936                }
937                _ => {
938                    // Copy one whole UTF-8 character so multi-byte text survives.
939                    let rest = &self.text[self.position..];
940                    let character = rest.chars().next().ok_or_else(|| JsonError {
941                        message: "invalid UTF-8".to_string(),
942                        offset: self.position,
943                    })?;
944                    out.push(character);
945                    self.position += character.len_utf8();
946                }
947            }
948        }
949    }
950
951    /// A bare identifier used as a property key.
952    ///
953    /// The reference runs this through the full JS identifier tables, so it accepts non-ASCII
954    /// letters. `is_alphanumeric` covers the same ground without pulling those tables into
955    /// the JSON parser; an identifier the two disagree about would have to start with a
956    /// non-ASCII, non-letter character, which no realistic config file does.
957    fn identifier(&mut self) -> Result<String, JsonError> {
958        let start = self.position;
959        while self
960            .text
961            .get(start..)
962            .and_then(|rest| rest.chars().next())
963            .is_some_and(|_| self.position < self.text.len())
964        {
965            let character = self.text[self.position..]
966                .chars()
967                .next()
968                .expect("the loop condition checked");
969            let keep = if self.position == start {
970                is_identifier_start(character as u32 as u8)
971                    || character.is_alphabetic()
972                    || character == '_'
973                    || character == '$'
974            } else {
975                character.is_alphanumeric() || character == '_' || character == '$'
976            };
977            if !keep {
978                break;
979            }
980            self.position += character.len_utf8();
981        }
982        if self.position == start {
983            return self.error("expected an identifier");
984        }
985        Ok(self.text[start..self.position].to_string())
986    }
987
988    fn array(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
989        self.position += 1;
990        let mut elements = Vec::new();
991        self.skip_whitespace();
992        if matches!(self.peek(), Some(b']')) {
993            self.position += 1;
994            return Ok(Value::Object(interp.new_array(elements)));
995        }
996        loop {
997            elements.push(self.value(interp)?);
998            self.skip_whitespace();
999            match self.peek() {
1000                Some(b',') => {
1001                    self.position += 1;
1002                    // A trailing comma closes the array in the extended dialect.
1003                    if self.ext {
1004                        self.skip_whitespace();
1005                        if matches!(self.peek(), Some(b']')) {
1006                            self.position += 1;
1007                            return Ok(Value::Object(interp.new_array(elements)));
1008                        }
1009                    }
1010                }
1011                Some(b']') => {
1012                    self.position += 1;
1013                    return Ok(Value::Object(interp.new_array(elements)));
1014                }
1015                _ => return self.error("expected ',' or ']'"),
1016            }
1017        }
1018    }
1019
1020    fn object(&mut self, interp: &mut Interp<'_>) -> Result<Value, JsonError> {
1021        self.position += 1;
1022        let proto = interp.realm.object_proto.clone();
1023        let object = interp.new_object(Some(proto));
1024        self.skip_whitespace();
1025        if matches!(self.peek(), Some(b'}')) {
1026            self.position += 1;
1027            return Ok(Value::Object(object));
1028        }
1029        loop {
1030            self.skip_whitespace();
1031            let key = match self.peek() {
1032                Some(b'"') => self.string()?,
1033                // A bare identifier as a key, e.g. `{ z2: null }`.
1034                Some(b'\'') if self.ext => self.string()?,
1035                Some(byte) if self.ext && is_identifier_start(byte) => self.identifier()?,
1036                _ => return self.error("expecting property name"),
1037            };
1038            self.skip_whitespace();
1039            if !matches!(self.peek(), Some(b':')) {
1040                return self.error("expected ':'");
1041            }
1042            self.position += 1;
1043            let value = self.value(interp)?;
1044            object.define_data(&key, value);
1045            self.skip_whitespace();
1046            match self.peek() {
1047                Some(b',') => {
1048                    self.position += 1;
1049                    // A trailing comma closes the object in the extended dialect.
1050                    if self.ext {
1051                        self.skip_whitespace();
1052                        if matches!(self.peek(), Some(b'}')) {
1053                            self.position += 1;
1054                            return Ok(Value::Object(object));
1055                        }
1056                    }
1057                }
1058                Some(b'}') => {
1059                    self.position += 1;
1060                    return Ok(Value::Object(object));
1061                }
1062                _ => return self.error("expected ',' or '}'"),
1063            }
1064        }
1065    }
1066}