Skip to main content

quickjs_jit_stdlib/llrt/llrt_json/
parse.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_json/src/parse.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5
6use crate::utils::bytes::ObjectBytes;
7use rquickjs::{Array, Ctx, Exception, IntoJs, Null, Object, Result, Undefined, Value};
8use simd_json::{Node, StaticNode};
9
10pub fn json_parse_string<'js>(ctx: Ctx<'js>, bytes: ObjectBytes<'js>) -> Result<Value<'js>> {
11    let bytes = bytes.as_bytes(&ctx)?;
12    json_parse(&ctx, bytes)
13}
14
15pub fn json_parse<'js, T: Into<Vec<u8>>>(ctx: &Ctx<'js>, json: T) -> Result<Value<'js>> {
16    let mut json: Vec<u8> = json.into();
17    let tape = match simd_json::to_tape(&mut json) {
18        Ok(tape) => tape,
19        Err(err) => {
20            // simd_json is strict about lone / unpaired surrogate escapes
21            // (`\uXXXX` where XXXX is a surrogate code point). Fall back to
22            // QuickJS's native `JSON.parse`, which is more permissive and is
23            // needed for spec compliance with content that round-trips
24            // through `JSON.stringify` of strings containing lone surrogates.
25            if err.character() == Some('u') {
26                if let Ok(value) = ctx.json_parse(json.as_slice()) {
27                    return Ok(value);
28                }
29            }
30            let mut itoa = itoa::Buffer::new();
31            let mut error_msg = String::with_capacity(256);
32            let json_length = json.len();
33            if json_length < 128 {
34                error_msg.reserve(json_length);
35                error_msg.push('\"');
36                error_msg.push_str(&std::string::String::from_utf8_lossy(&json));
37                error_msg.push_str("\" ");
38            }
39
40            error_msg.push_str("not valid JSON at index ");
41            error_msg.push_str(itoa.format(err.index()));
42            if let Some(char) = err.character() {
43                error_msg.push_str(" ('");
44                error_msg.push(char);
45                error_msg.push_str("')");
46            }
47            return Err(Exception::throw_syntax(ctx, &error_msg));
48        }
49    };
50    let tape = tape.0;
51
52    if let Some(first) = tape.first() {
53        return match first {
54            Node::String(value) => value.into_js(ctx),
55            Node::Static(node) => static_node_to_value(ctx, *node),
56            _ => parse_node(ctx, &tape, 0).map(|(value, _)| value),
57        };
58    }
59
60    Undefined.into_js(ctx)
61}
62
63#[inline(always)]
64fn static_node_to_value<'js>(ctx: &Ctx<'js>, node: StaticNode) -> Result<Value<'js>> {
65    match node {
66        StaticNode::I64(value) => value.into_js(ctx),
67        StaticNode::U64(value) => value.into_js(ctx),
68        StaticNode::F64(value) => value.into_js(ctx),
69        StaticNode::Bool(value) => value.into_js(ctx),
70        StaticNode::Null => Null.into_js(ctx),
71    }
72}
73
74fn parse_node<'js>(ctx: &Ctx<'js>, tape: &[Node], index: usize) -> Result<(Value<'js>, usize)> {
75    match tape[index] {
76        Node::String(value) => Ok((value.into_js(ctx)?, index + 1)),
77        Node::Static(node) => Ok((static_node_to_value(ctx, node)?, index + 1)),
78        Node::Object { len, .. } => {
79            let js_object = Object::new(ctx.clone())?;
80            let mut current_index = index + 1;
81
82            for _ in 0..len {
83                if let Node::String(key) = tape[current_index] {
84                    current_index += 1;
85                    let (value, new_index) = parse_node(ctx, tape, current_index)?;
86                    current_index = new_index;
87                    js_object.set(key, value)?;
88                }
89            }
90
91            Ok((js_object.into_value(), current_index))
92        }
93        Node::Array { len, .. } => {
94            let js_array = Array::new(ctx.clone())?;
95            let mut current_index = index + 1;
96
97            for i in 0..len {
98                let (value, new_index) = parse_node(ctx, tape, current_index)?;
99                current_index = new_index;
100                js_array.set(i, value)?;
101            }
102
103            Ok((js_array.into_value(), current_index))
104        }
105    }
106}