Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / infra / json.lucb

#==============================================================================================
#
#   json - Infra's JSON operations: parsing and serializing through the JavaScript JSON object
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Infra/JSON.cpp (lines 1-174). Every operation goes through a
#       JavaScript value: %JSON.parse%, %JSON.stringify%, Array and Object creation. Serializing
#       runs over the phase-1 stand-ins of external/lib_js (strings, Arrays, ordinary objects,
#       JSON.stringify; DESIGN.md §3.6); parsing calls into the JavaScript engine (luce-js,
#       phase 3) and traps with "unported (P3)".
#
#       Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: JavaScript values =======================================================================

## Ported from Libraries/LibWeb/Infra/JSON.cpp:19 Web::Infra::parse_json_string_to_javascript_value.
# https://infra.spec.whatwg.org/#parse-a-json-string-to-a-javascript-value
pub func infra_parse_json_string_to_javascript_value(realm: Realm*, string: ak.StringView) -> JsValue!:
    # auto& vm = realm.vm();

    # 1. Return ? Call(%JSON.parse%, undefined, « string »).
    trap("unported (P3): Web::Infra::parse_json_string_to_javascript_value calls %JSON.parse% (luce-js)")

## Ported from Libraries/LibWeb/Infra/JSON.cpp:28 Web::Infra::parse_json_bytes_to_javascript_value.
# https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
pub func infra_parse_json_bytes_to_javascript_value(realm: Realm*, bytes: const u8[]) -> JsValue!:
    # 1. Let string be the result of running UTF-8 decode on bytes.
    var decoder = text_codec.Utf8Decoder(decoder_base = text_codec.Decoder(vtable = &text_codec.utf8_decoder_vtable.decoder_vtable, class_id = text_codec.utf8_decoder_class.first_id))
    let string = try text_codec.decoder_to_utf8(decoder.decoder(), ak.string_view_from_bytes(bytes))

    # 2. Return the result of parsing a JSON string to an Infra value given string.
    return try infra_parse_json_string_to_javascript_value(realm, ak.string_bytes_as_string_view(&string))

## Ported from Libraries/LibWeb/Infra/JSON.cpp:41 Web::Infra::serialize_javascript_value_to_json_string.
# https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
pub func infra_serialize_javascript_value_to_json_string(vm: Vm*, value: JsValue) -> ak.String!:
    let realm = vm_current_realm(vm) else trap("serialize_javascript_value_to_json_string: no current realm")

    # 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
    let result = try js_json_stringify(realm, value)

    # 2. If result is undefined, then throw a TypeError.
    let string = result else try idl_throw(.idl_simple_exception(IdlSimpleException(type_ = IdlSimpleExceptionType.type_error, message = .string_view(ak.sv("Result of stringifying value must not be undefined")))))

    # 3. Assert: result is a string.
    # 4. Return result.
    return string

## Ported from Libraries/LibWeb/Infra/JSON.cpp:60 Web::Infra::serialize_javascript_value_to_json_bytes.
# https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-json-bytes
pub func infra_serialize_javascript_value_to_json_bytes(vm: Vm*, value: JsValue) -> ak.ByteBuffer!:
    # 1. Let string be the result of serializing a JavaScript value to a JSON string given value.
    let string = try infra_serialize_javascript_value_to_json_string(vm, value)

    # 2. Return the result of running UTF-8 encode on string.
    # NOTE: LibJS strings are stored as UTF-8.
    let view = ak.string_bytes_as_string_view(&string)
    return try ak.byte_buffer_copy_span_u8(ak.string_view_bytes(&view))

# mark: Infra values ============================================================================

## Ported from Libraries/LibWeb/Infra/JSON.cpp:71 Web::Infra::convert_an_infra_value_to_a_json_compatible_javascript_value.
# https://infra.spec.whatwg.org/#convert-an-infra-value-to-a-json-compatible-javascript-value
func infra_convert_an_infra_value_to_a_json_compatible_javascript_value(realm: Realm*, value: const InfraJsonTopLevel*) -> JsValue:
    let vm = realm_vm(realm)

    match *value:
        .json_value(json_value):
            # 1. If value is a string, boolean, number, or null, then return value.
            match json_value:
                .json_base_value(base_value):
                    return infra_convert_a_json_base_value(vm, base_value)
                .vector(list_value):
                    # 2. If value is a list, then:

                    # 1. Let jsValue be ! ArrayCreate(0).
                    let js_value = js_array_create(realm, 0) else trap("MUST: Array::create")

                    # 2. Let i be 0.
                    var index: u32 = 0

                    # 3. For each listItem of value:
                    for list_item in ak.vector_span_const(&list_value):
                        # 1. Let listItemJSValue be the result of converting an Infra value to a JSON-compatible JavaScript value,
                        #    given listItem.
                        let list_item_value = InfraJsonTopLevel.json_value(InfraJsonValue.json_base_value(list_item))
                        let list_item_js_value = infra_convert_an_infra_value_to_a_json_compatible_javascript_value(realm, &list_item_value)

                        # 2. Perform ! CreateDataPropertyOrThrow(jsValue, ! ToString(i), listItemJSValue).
                        js_array_create_data_property_or_throw(js_value, index, list_item_js_value)

                        # 3. Set i to i + 1.
                        index += 1

                    # 4. Return jsValue.
                    return js_value_from_object((JsObject*)js_value)

        .infra_json_object(map_value):
            # 3. Assert: value is a map.

            # 4. Let jsValue be ! OrdinaryObjectCreate(null).
            let js_value = js_object_create(realm)

            # 5. For each mapKey → mapValue of value:
            for map_entry in ak.ordered_hash_map_begin_const(&map_value.value):
                # 1. Assert: mapKey is a string.
                # 2. Let mapValueJSValue be the result of converting an Infra value to a JSON-compatible JavaScript value,
                #    given mapValue.
                let map_value_js_value = infra_convert_an_infra_value_to_a_json_compatible_javascript_value(realm, &map_entry.value)

                # 3. Perform ! CreateDataPropertyOrThrow(jsValue, mapKey, mapValueJSValue).
                js_object_create_data_property_or_throw((JsObject*)js_value, map_entry.key, map_value_js_value)

            # 6. Return jsValue.
            return js_value_from_object((JsObject*)js_value)

## Step 1 of convert_an_infra_value_to_a_json_compatible_javascript_value: a string, boolean, number or null
## as the JS value it is (JS::PrimitiveString::create, JS::Value(bool), JS::Value(u16 or u32), js_null()).
func infra_convert_a_json_base_value(vm: Vm*, base_value: InfraJsonBaseValue) -> JsValue:
    return match base_value:
        .string(string) => js_primitive_string_create_string(vm, string)
        .bool_(boolean) => js_value_from_bool(boolean)
        .u16_(number) => js_value_from_f64((f64)number)
        .u32_(number) => js_value_from_f64((f64)number)
        .empty => js_null()

## Ported from Libraries/LibWeb/Infra/JSON.cpp:148 Web::Infra::serialize_an_infra_value_to_a_json_string.
# https://infra.spec.whatwg.org/#serialize-an-infra-value-to-a-json-string
pub func infra_serialize_an_infra_value_to_a_json_string(realm: Realm*, value: InfraJsonTopLevel) -> ak.String:
    # auto& vm = realm.vm();

    # 1. Let jsValue be the result of converting an Infra value to a JSON-compatible JavaScript value, given value.
    let js_value = infra_convert_an_infra_value_to_a_json_compatible_javascript_value(realm, &value)

    # 2. Return ! Call(%JSON.stringify%, undefined, « jsValue »).
    # Spec Note: Since no additional arguments are passed to %JSON.stringify%, the resulting string will have no
    #            whitespace inserted.
    let result = js_json_stringify(realm, js_value) else trap("MUST: Call(%JSON.stringify%)")
    return result else trap("VERIFY: result.is_string()")

## Ported from Libraries/LibWeb/Infra/JSON.cpp:164 Web::Infra::serialize_an_infra_value_to_json_bytes.
# https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-json-bytes
pub func infra_serialize_an_infra_value_to_json_bytes(realm: Realm*, value: InfraJsonTopLevel) -> ak.ByteBuffer:
    # 1. Let string be the result of serializing an Infra value to a JSON string, given value.
    let string = infra_serialize_an_infra_value_to_a_json_string(realm, value)

    # 2. Return the result of running UTF-8 encode on string. [ENCODING]
    # NOTE: LibJS strings are stored as UTF-8.
    let view = ak.string_bytes_as_string_view(&string)
    return ak.byte_buffer_copy_span_u8(ak.string_view_bytes(&view)) else trap("MUST: ByteBuffer::copy")