JSONObject.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibJS/Runtime/Object.h>
  8. namespace JS {
  9. class JSONObject final : public Object {
  10. JS_OBJECT(JSONObject, Object);
  11. JS_DECLARE_ALLOCATOR(JSONObject);
  12. public:
  13. virtual void initialize(Realm&) override;
  14. virtual ~JSONObject() override = default;
  15. // The base implementation of stringify is exposed because it is used by
  16. // test-js to communicate between the JS tests and the C++ test runner.
  17. static ThrowCompletionOr<Optional<ByteString>> stringify_impl(VM&, Value value, Value replacer, Value space);
  18. static Value parse_json_value(VM&, JsonValue const&);
  19. private:
  20. explicit JSONObject(Realm&);
  21. struct StringifyState {
  22. GCPtr<FunctionObject> replacer_function;
  23. HashTable<GCPtr<Object>> seen_objects;
  24. ByteString indent { ByteString::empty() };
  25. ByteString gap;
  26. Optional<Vector<ByteString>> property_list;
  27. };
  28. // Stringify helpers
  29. static ThrowCompletionOr<Optional<ByteString>> serialize_json_property(VM&, StringifyState&, PropertyKey const& key, Object* holder);
  30. static ThrowCompletionOr<ByteString> serialize_json_object(VM&, StringifyState&, Object&);
  31. static ThrowCompletionOr<ByteString> serialize_json_array(VM&, StringifyState&, Object&);
  32. static ByteString quote_json_string(ByteString);
  33. // Parse helpers
  34. static Object* parse_json_object(VM&, JsonObject const&);
  35. static Array* parse_json_array(VM&, JsonArray const&);
  36. static ThrowCompletionOr<Value> internalize_json_property(VM&, Object* holder, PropertyKey const& name, FunctionObject& reviver);
  37. JS_DECLARE_NATIVE_FUNCTION(stringify);
  38. JS_DECLARE_NATIVE_FUNCTION(parse);
  39. };
  40. }