summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/JSONObject.h
blob: 85ab019b06e93dafd5f538648ee9d7e455958be5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <LibJS/Runtime/Object.h>

namespace JS {

class JSONObject final : public Object {
    JS_OBJECT(JSONObject, Object);

public:
    virtual ThrowCompletionOr<void> initialize(Realm&) override;
    virtual ~JSONObject() override = default;

    // The base implementation of stringify is exposed because it is used by
    // test-js to communicate between the JS tests and the C++ test runner.
    static ThrowCompletionOr<DeprecatedString> stringify_impl(VM&, Value value, Value replacer, Value space);

    static Value parse_json_value(VM&, JsonValue const&);

private:
    explicit JSONObject(Realm&);

    struct StringifyState {
        GCPtr<FunctionObject> replacer_function;
        HashTable<GCPtr<Object>> seen_objects;
        DeprecatedString indent { DeprecatedString::empty() };
        DeprecatedString gap;
        Optional<Vector<DeprecatedString>> property_list;
    };

    // Stringify helpers
    static ThrowCompletionOr<DeprecatedString> serialize_json_property(VM&, StringifyState&, PropertyKey const& key, Object* holder);
    static ThrowCompletionOr<DeprecatedString> serialize_json_object(VM&, StringifyState&, Object&);
    static ThrowCompletionOr<DeprecatedString> serialize_json_array(VM&, StringifyState&, Object&);
    static DeprecatedString quote_json_string(DeprecatedString);

    // Parse helpers
    static Object* parse_json_object(VM&, JsonObject const&);
    static Array* parse_json_array(VM&, JsonArray const&);
    static ThrowCompletionOr<Value> internalize_json_property(VM&, Object* holder, PropertyKey const& name, FunctionObject& reviver);

    JS_DECLARE_NATIVE_FUNCTION(stringify);
    JS_DECLARE_NATIVE_FUNCTION(parse);
};

}