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