JSONObject.cpp 19 KB

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