JSONObject.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <AK/JsonArray.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonParser.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/TypeCasts.h>
  12. #include <AK/Utf16View.h>
  13. #include <AK/Utf8View.h>
  14. #include <LibJS/Runtime/AbstractOperations.h>
  15. #include <LibJS/Runtime/Array.h>
  16. #include <LibJS/Runtime/BigIntObject.h>
  17. #include <LibJS/Runtime/BooleanObject.h>
  18. #include <LibJS/Runtime/Error.h>
  19. #include <LibJS/Runtime/FunctionObject.h>
  20. #include <LibJS/Runtime/GlobalObject.h>
  21. #include <LibJS/Runtime/JSONObject.h>
  22. #include <LibJS/Runtime/NumberObject.h>
  23. #include <LibJS/Runtime/Object.h>
  24. #include <LibJS/Runtime/StringObject.h>
  25. #include <LibJS/Runtime/ValueInlines.h>
  26. namespace JS {
  27. JS_DEFINE_ALLOCATOR(JSONObject);
  28. JSONObject::JSONObject(Realm& realm)
  29. : Object(ConstructWithPrototypeTag::Tag, realm.intrinsics().object_prototype())
  30. {
  31. }
  32. void JSONObject::initialize(Realm& realm)
  33. {
  34. auto& vm = this->vm();
  35. Base::initialize(realm);
  36. u8 attr = Attribute::Writable | Attribute::Configurable;
  37. define_native_function(realm, vm.names.stringify, stringify, 3, attr);
  38. define_native_function(realm, vm.names.parse, parse, 2, attr);
  39. // 25.5.3 JSON [ @@toStringTag ], https://tc39.es/ecma262/#sec-json-@@tostringtag
  40. define_direct_property(vm.well_known_symbol_to_string_tag(), PrimitiveString::create(vm, "JSON"_string), Attribute::Configurable);
  41. }
  42. // 25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] ), https://tc39.es/ecma262/#sec-json.stringify
  43. ThrowCompletionOr<Optional<ByteString>> JSONObject::stringify_impl(VM& vm, Value value, Value replacer, Value space)
  44. {
  45. auto& realm = *vm.current_realm();
  46. StringifyState state;
  47. if (replacer.is_object()) {
  48. if (replacer.as_object().is_function()) {
  49. state.replacer_function = &replacer.as_function();
  50. } else {
  51. auto is_array = TRY(replacer.is_array(vm));
  52. if (is_array) {
  53. auto& replacer_object = replacer.as_object();
  54. auto replacer_length = TRY(length_of_array_like(vm, replacer_object));
  55. Vector<ByteString> list;
  56. for (size_t i = 0; i < replacer_length; ++i) {
  57. auto replacer_value = TRY(replacer_object.get(i));
  58. Optional<ByteString> item;
  59. if (replacer_value.is_string()) {
  60. item = replacer_value.as_string().byte_string();
  61. } else if (replacer_value.is_number()) {
  62. item = MUST(replacer_value.to_byte_string(vm));
  63. } else if (replacer_value.is_object()) {
  64. auto& value_object = replacer_value.as_object();
  65. if (is<StringObject>(value_object) || is<NumberObject>(value_object))
  66. item = TRY(replacer_value.to_byte_string(vm));
  67. }
  68. if (item.has_value() && !list.contains_slow(*item)) {
  69. list.append(*item);
  70. }
  71. }
  72. state.property_list = list;
  73. }
  74. }
  75. }
  76. if (space.is_object()) {
  77. auto& space_object = space.as_object();
  78. if (is<NumberObject>(space_object))
  79. space = TRY(space.to_number(vm));
  80. else if (is<StringObject>(space_object))
  81. space = TRY(space.to_primitive_string(vm));
  82. }
  83. if (space.is_number()) {
  84. auto space_mv = MUST(space.to_integer_or_infinity(vm));
  85. space_mv = min(10, space_mv);
  86. state.gap = space_mv < 1 ? ByteString::empty() : ByteString::repeated(' ', space_mv);
  87. } else if (space.is_string()) {
  88. auto string = space.as_string().byte_string();
  89. if (string.length() <= 10)
  90. state.gap = string;
  91. else
  92. state.gap = string.substring(0, 10);
  93. } else {
  94. state.gap = ByteString::empty();
  95. }
  96. auto wrapper = Object::create(realm, realm.intrinsics().object_prototype());
  97. MUST(wrapper->create_data_property_or_throw(ByteString::empty(), value));
  98. return serialize_json_property(vm, state, ByteString::empty(), wrapper);
  99. }
  100. // 25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] ), https://tc39.es/ecma262/#sec-json.stringify
  101. JS_DEFINE_NATIVE_FUNCTION(JSONObject::stringify)
  102. {
  103. if (!vm.argument_count())
  104. return js_undefined();
  105. auto value = vm.argument(0);
  106. auto replacer = vm.argument(1);
  107. auto space = vm.argument(2);
  108. auto maybe_string = TRY(stringify_impl(vm, value, replacer, space));
  109. if (!maybe_string.has_value())
  110. return js_undefined();
  111. return PrimitiveString::create(vm, maybe_string.release_value());
  112. }
  113. // 25.5.2.1 SerializeJSONProperty ( state, key, holder ), https://tc39.es/ecma262/#sec-serializejsonproperty
  114. ThrowCompletionOr<Optional<ByteString>> JSONObject::serialize_json_property(VM& vm, StringifyState& state, PropertyKey const& key, Object* holder)
  115. {
  116. // 1. Let value be ? Get(holder, key).
  117. auto value = TRY(holder->get(key));
  118. // 2. If Type(value) is Object or BigInt, then
  119. if (value.is_object() || value.is_bigint()) {
  120. // a. Let toJSON be ? GetV(value, "toJSON").
  121. auto to_json = TRY(value.get(vm, vm.names.toJSON));
  122. // b. If IsCallable(toJSON) is true, then
  123. if (to_json.is_function()) {
  124. // i. Set value to ? Call(toJSON, value, « key »).
  125. value = TRY(call(vm, to_json.as_function(), value, PrimitiveString::create(vm, key.to_string())));
  126. }
  127. }
  128. // 3. If state.[[ReplacerFunction]] is not undefined, then
  129. if (state.replacer_function) {
  130. // a. Set value to ? Call(state.[[ReplacerFunction]], holder, « key, value »).
  131. value = TRY(call(vm, *state.replacer_function, holder, PrimitiveString::create(vm, key.to_string()), value));
  132. }
  133. // 4. If Type(value) is Object, then
  134. if (value.is_object()) {
  135. auto& value_object = value.as_object();
  136. // a. If value has a [[NumberData]] internal slot, then
  137. if (is<NumberObject>(value_object)) {
  138. // i. Set value to ? ToNumber(value).
  139. value = TRY(value.to_number(vm));
  140. }
  141. // b. Else if value has a [[StringData]] internal slot, then
  142. else if (is<StringObject>(value_object)) {
  143. // i. Set value to ? ToString(value).
  144. value = TRY(value.to_primitive_string(vm));
  145. }
  146. // c. Else if value has a [[BooleanData]] internal slot, then
  147. else if (is<BooleanObject>(value_object)) {
  148. // i. Set value to value.[[BooleanData]].
  149. value = Value(static_cast<BooleanObject&>(value_object).boolean());
  150. }
  151. // d. Else if value has a [[BigIntData]] internal slot, then
  152. else if (is<BigIntObject>(value_object)) {
  153. // i. Set value to value.[[BigIntData]].
  154. value = Value(&static_cast<BigIntObject&>(value_object).bigint());
  155. }
  156. }
  157. // 5. If value is null, return "null".
  158. if (value.is_null())
  159. return "null"sv;
  160. // 6. If value is true, return "true".
  161. // 7. If value is false, return "false".
  162. if (value.is_boolean())
  163. return value.as_bool() ? "true"sv : "false"sv;
  164. // 8. If Type(value) is String, return QuoteJSONString(value).
  165. if (value.is_string())
  166. return quote_json_string(value.as_string().byte_string());
  167. // 9. If Type(value) is Number, then
  168. if (value.is_number()) {
  169. // a. If value is finite, return ! ToString(value).
  170. if (value.is_finite_number())
  171. return MUST(value.to_byte_string(vm));
  172. // b. Return "null".
  173. return "null"sv;
  174. }
  175. // 10. If Type(value) is BigInt, throw a TypeError exception.
  176. if (value.is_bigint())
  177. return vm.throw_completion<TypeError>(ErrorType::JsonBigInt);
  178. // 11. If Type(value) is Object and IsCallable(value) is false, then
  179. if (value.is_object() && !value.is_function()) {
  180. // a. Let isArray be ? IsArray(value).
  181. auto is_array = TRY(value.is_array(vm));
  182. // b. If isArray is true, return ? SerializeJSONArray(state, value).
  183. if (is_array)
  184. return TRY(serialize_json_array(vm, state, value.as_object()));
  185. // c. Return ? SerializeJSONObject(state, value).
  186. return TRY(serialize_json_object(vm, state, value.as_object()));
  187. }
  188. // 12. Return undefined.
  189. return Optional<ByteString> {};
  190. }
  191. // 25.5.2.4 SerializeJSONObject ( state, value ), https://tc39.es/ecma262/#sec-serializejsonobject
  192. ThrowCompletionOr<ByteString> JSONObject::serialize_json_object(VM& vm, StringifyState& state, Object& object)
  193. {
  194. if (state.seen_objects.contains(&object))
  195. return vm.throw_completion<TypeError>(ErrorType::JsonCircular);
  196. state.seen_objects.set(&object);
  197. ByteString previous_indent = state.indent;
  198. state.indent = ByteString::formatted("{}{}", state.indent, state.gap);
  199. Vector<ByteString> property_strings;
  200. auto process_property = [&](PropertyKey const& key) -> ThrowCompletionOr<void> {
  201. if (key.is_symbol())
  202. return {};
  203. auto serialized_property_string = TRY(serialize_json_property(vm, state, key, &object));
  204. if (serialized_property_string.has_value()) {
  205. property_strings.append(ByteString::formatted(
  206. "{}:{}{}",
  207. quote_json_string(key.to_string()),
  208. state.gap.is_empty() ? "" : " ",
  209. serialized_property_string));
  210. }
  211. return {};
  212. };
  213. if (state.property_list.has_value()) {
  214. auto property_list = state.property_list.value();
  215. for (auto& property : property_list)
  216. TRY(process_property(property));
  217. } else {
  218. auto property_list = TRY(object.enumerable_own_property_names(PropertyKind::Key));
  219. for (auto& property : property_list)
  220. TRY(process_property(property.as_string().byte_string()));
  221. }
  222. StringBuilder builder;
  223. if (property_strings.is_empty()) {
  224. builder.append("{}"sv);
  225. } else {
  226. bool first = true;
  227. builder.append('{');
  228. if (state.gap.is_empty()) {
  229. for (auto& property_string : property_strings) {
  230. if (!first)
  231. builder.append(',');
  232. first = false;
  233. builder.append(property_string);
  234. }
  235. } else {
  236. builder.append('\n');
  237. builder.append(state.indent);
  238. auto separator = ByteString::formatted(",\n{}", state.indent);
  239. for (auto& property_string : property_strings) {
  240. if (!first)
  241. builder.append(separator);
  242. first = false;
  243. builder.append(property_string);
  244. }
  245. builder.append('\n');
  246. builder.append(previous_indent);
  247. }
  248. builder.append('}');
  249. }
  250. state.seen_objects.remove(&object);
  251. state.indent = previous_indent;
  252. return builder.to_byte_string();
  253. }
  254. // 25.5.2.5 SerializeJSONArray ( state, value ), https://tc39.es/ecma262/#sec-serializejsonarray
  255. ThrowCompletionOr<ByteString> JSONObject::serialize_json_array(VM& vm, StringifyState& state, Object& object)
  256. {
  257. if (state.seen_objects.contains(&object))
  258. return vm.throw_completion<TypeError>(ErrorType::JsonCircular);
  259. state.seen_objects.set(&object);
  260. ByteString previous_indent = state.indent;
  261. state.indent = ByteString::formatted("{}{}", state.indent, state.gap);
  262. Vector<ByteString> property_strings;
  263. auto length = TRY(length_of_array_like(vm, object));
  264. // Optimization
  265. property_strings.ensure_capacity(length);
  266. for (size_t i = 0; i < length; ++i) {
  267. auto serialized_property_string = TRY(serialize_json_property(vm, state, i, &object));
  268. if (!serialized_property_string.has_value()) {
  269. property_strings.append("null"sv);
  270. } else {
  271. property_strings.append(serialized_property_string.release_value());
  272. }
  273. }
  274. StringBuilder builder;
  275. if (property_strings.is_empty()) {
  276. builder.append("[]"sv);
  277. } else {
  278. if (state.gap.is_empty()) {
  279. builder.append('[');
  280. bool first = true;
  281. for (auto& property_string : property_strings) {
  282. if (!first)
  283. builder.append(',');
  284. first = false;
  285. builder.append(property_string);
  286. }
  287. builder.append(']');
  288. } else {
  289. builder.append("[\n"sv);
  290. builder.append(state.indent);
  291. auto separator = ByteString::formatted(",\n{}", state.indent);
  292. bool first = true;
  293. for (auto& property_string : property_strings) {
  294. if (!first)
  295. builder.append(separator);
  296. first = false;
  297. builder.append(property_string);
  298. }
  299. builder.append('\n');
  300. builder.append(previous_indent);
  301. builder.append(']');
  302. }
  303. }
  304. state.seen_objects.remove(&object);
  305. state.indent = previous_indent;
  306. return builder.to_byte_string();
  307. }
  308. // 25.5.2.2 QuoteJSONString ( value ), https://tc39.es/ecma262/#sec-quotejsonstring
  309. ByteString JSONObject::quote_json_string(ByteString string)
  310. {
  311. // 1. Let product be the String value consisting solely of the code unit 0x0022 (QUOTATION MARK).
  312. StringBuilder builder;
  313. builder.append('"');
  314. // 2. For each code point C of StringToCodePoints(value), do
  315. auto utf_view = Utf8View(string);
  316. for (auto code_point : utf_view) {
  317. // a. If C is listed in the “Code Point” column of Table 70, then
  318. // i. Set product to the string-concatenation of product and the escape sequence for C as specified in the “Escape Sequence” column of the corresponding row.
  319. switch (code_point) {
  320. case '\b':
  321. builder.append("\\b"sv);
  322. break;
  323. case '\t':
  324. builder.append("\\t"sv);
  325. break;
  326. case '\n':
  327. builder.append("\\n"sv);
  328. break;
  329. case '\f':
  330. builder.append("\\f"sv);
  331. break;
  332. case '\r':
  333. builder.append("\\r"sv);
  334. break;
  335. case '"':
  336. builder.append("\\\""sv);
  337. break;
  338. case '\\':
  339. builder.append("\\\\"sv);
  340. break;
  341. default:
  342. // b. Else if C has a numeric value less than 0x0020 (SPACE), or if C has the same numeric value as a leading surrogate or trailing surrogate, then
  343. if (code_point < 0x20 || is_unicode_surrogate(code_point)) {
  344. // i. Let unit be the code unit whose numeric value is that of C.
  345. // ii. Set product to the string-concatenation of product and UnicodeEscape(unit).
  346. builder.appendff("\\u{:04x}", code_point);
  347. }
  348. // c. Else,
  349. else {
  350. // i. Set product to the string-concatenation of product and UTF16EncodeCodePoint(C).
  351. builder.append_code_point(code_point);
  352. }
  353. }
  354. }
  355. // 3. Set product to the string-concatenation of product and the code unit 0x0022 (QUOTATION MARK).
  356. builder.append('"');
  357. // 4. Return product.
  358. return builder.to_byte_string();
  359. }
  360. // 25.5.1 JSON.parse ( text [ , reviver ] ), https://tc39.es/ecma262/#sec-json.parse
  361. JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
  362. {
  363. auto& realm = *vm.current_realm();
  364. auto string = TRY(vm.argument(0).to_byte_string(vm));
  365. auto reviver = vm.argument(1);
  366. auto json = JsonValue::from_string(string);
  367. if (json.is_error())
  368. return vm.throw_completion<SyntaxError>(ErrorType::JsonMalformed);
  369. Value unfiltered = parse_json_value(vm, json.value());
  370. if (reviver.is_function()) {
  371. auto root = Object::create(realm, realm.intrinsics().object_prototype());
  372. auto root_name = ByteString::empty();
  373. MUST(root->create_data_property_or_throw(root_name, unfiltered));
  374. return internalize_json_property(vm, root, root_name, reviver.as_function());
  375. }
  376. return unfiltered;
  377. }
  378. Value JSONObject::parse_json_value(VM& vm, JsonValue const& value)
  379. {
  380. if (value.is_object())
  381. return Value(parse_json_object(vm, value.as_object()));
  382. if (value.is_array())
  383. return Value(parse_json_array(vm, value.as_array()));
  384. if (value.is_null())
  385. return js_null();
  386. if (auto double_value = value.get_double_with_precision_loss(); double_value.has_value())
  387. return Value(double_value.value());
  388. if (value.is_string())
  389. return PrimitiveString::create(vm, value.as_string());
  390. if (value.is_bool())
  391. return Value(static_cast<bool>(value.as_bool()));
  392. VERIFY_NOT_REACHED();
  393. }
  394. Object* JSONObject::parse_json_object(VM& vm, JsonObject const& json_object)
  395. {
  396. auto& realm = *vm.current_realm();
  397. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  398. json_object.for_each_member([&](auto& key, auto& value) {
  399. object->define_direct_property(key, parse_json_value(vm, value), default_attributes);
  400. });
  401. return object;
  402. }
  403. Array* JSONObject::parse_json_array(VM& vm, JsonArray const& json_array)
  404. {
  405. auto& realm = *vm.current_realm();
  406. auto array = MUST(Array::create(realm, 0));
  407. size_t index = 0;
  408. json_array.for_each([&](auto& value) {
  409. array->define_direct_property(index++, parse_json_value(vm, value), default_attributes);
  410. });
  411. return array;
  412. }
  413. // 25.5.1.1 InternalizeJSONProperty ( holder, name, reviver ), https://tc39.es/ecma262/#sec-internalizejsonproperty
  414. ThrowCompletionOr<Value> JSONObject::internalize_json_property(VM& vm, Object* holder, PropertyKey const& name, FunctionObject& reviver)
  415. {
  416. auto value = TRY(holder->get(name));
  417. if (value.is_object()) {
  418. auto is_array = TRY(value.is_array(vm));
  419. auto& value_object = value.as_object();
  420. auto process_property = [&](PropertyKey const& key) -> ThrowCompletionOr<void> {
  421. auto element = TRY(internalize_json_property(vm, &value_object, key, reviver));
  422. if (element.is_undefined())
  423. TRY(value_object.internal_delete(key));
  424. else
  425. TRY(value_object.create_data_property(key, element));
  426. return {};
  427. };
  428. if (is_array) {
  429. auto length = TRY(length_of_array_like(vm, value_object));
  430. for (size_t i = 0; i < length; ++i)
  431. TRY(process_property(i));
  432. } else {
  433. auto property_list = TRY(value_object.enumerable_own_property_names(Object::PropertyKind::Key));
  434. for (auto& property_key : property_list)
  435. TRY(process_property(property_key.as_string().byte_string()));
  436. }
  437. }
  438. return TRY(call(vm, reviver, holder, PrimitiveString::create(vm, name.to_string()), value));
  439. }
  440. }