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