JSONObject.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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(*realm.intrinsics().object_prototype())
  28. {
  29. }
  30. void JSONObject::initialize(Realm& realm)
  31. {
  32. auto& vm = this->vm();
  33. Object::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(), js_string(vm, "JSON"), Attribute::Configurable);
  39. }
  40. // 25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] ), https://tc39.es/ecma262/#sec-json.stringify
  41. ThrowCompletionOr<String> 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<String> list;
  54. for (size_t i = 0; i < replacer_length; ++i) {
  55. auto replacer_value = TRY(replacer_object.get(i));
  56. String item;
  57. if (replacer_value.is_string()) {
  58. item = replacer_value.as_string().string();
  59. } else if (replacer_value.is_number()) {
  60. item = MUST(replacer_value.to_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_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 ? String::empty() : String::repeated(' ', space_mv);
  85. } else if (space.is_string()) {
  86. auto string = space.as_string().string();
  87. if (string.length() <= 10)
  88. state.gap = string;
  89. else
  90. state.gap = string.substring(0, 10);
  91. } else {
  92. state.gap = String::empty();
  93. }
  94. auto* wrapper = Object::create(realm, realm.intrinsics().object_prototype());
  95. MUST(wrapper->create_data_property_or_throw(String::empty(), value));
  96. return serialize_json_property(vm, state, String::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 js_string(vm, string);
  110. }
  111. // 25.5.2.1 SerializeJSONProperty ( state, key, holder ), https://tc39.es/ecma262/#sec-serializejsonproperty
  112. ThrowCompletionOr<String> 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, js_string(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, js_string(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().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_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 String {};
  188. }
  189. // 25.5.2.4 SerializeJSONObject ( state, value ), https://tc39.es/ecma262/#sec-serializejsonobject
  190. ThrowCompletionOr<String> 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. String previous_indent = state.indent;
  196. state.indent = String::formatted("{}{}", state.indent, state.gap);
  197. Vector<String> 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(String::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().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 = String::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_string();
  251. }
  252. // 25.5.2.5 SerializeJSONArray ( state, value ), https://tc39.es/ecma262/#sec-serializejsonarray
  253. ThrowCompletionOr<String> 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. String previous_indent = state.indent;
  259. state.indent = String::formatted("{}{}", state.indent, state.gap);
  260. Vector<String> 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 = String::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_string();
  305. }
  306. // 25.5.2.2 QuoteJSONString ( value ), https://tc39.es/ecma262/#sec-quotejsonstring
  307. String JSONObject::quote_json_string(String string)
  308. {
  309. StringBuilder builder;
  310. builder.append('"');
  311. auto utf_view = Utf8View(string);
  312. for (auto code_point : utf_view) {
  313. switch (code_point) {
  314. case '\b':
  315. builder.append("\\b"sv);
  316. break;
  317. case '\t':
  318. builder.append("\\t"sv);
  319. break;
  320. case '\n':
  321. builder.append("\\n"sv);
  322. break;
  323. case '\f':
  324. builder.append("\\f"sv);
  325. break;
  326. case '\r':
  327. builder.append("\\r"sv);
  328. break;
  329. case '"':
  330. builder.append("\\\""sv);
  331. break;
  332. case '\\':
  333. builder.append("\\\\"sv);
  334. break;
  335. default:
  336. if (code_point < 0x20 || Utf16View::is_high_surrogate(code_point) || Utf16View::is_low_surrogate(code_point)) {
  337. builder.appendff("\\u{:04x}", code_point);
  338. } else {
  339. builder.append_code_point(code_point);
  340. }
  341. }
  342. }
  343. builder.append('"');
  344. return builder.to_string();
  345. }
  346. // 25.5.1 JSON.parse ( text [ , reviver ] ), https://tc39.es/ecma262/#sec-json.parse
  347. JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
  348. {
  349. auto& realm = *vm.current_realm();
  350. auto string = TRY(vm.argument(0).to_string(vm));
  351. auto reviver = vm.argument(1);
  352. auto json = JsonValue::from_string(string);
  353. if (json.is_error())
  354. return vm.throw_completion<SyntaxError>(ErrorType::JsonMalformed);
  355. Value unfiltered = parse_json_value(vm, json.value());
  356. if (reviver.is_function()) {
  357. auto* root = Object::create(realm, realm.intrinsics().object_prototype());
  358. auto root_name = String::empty();
  359. MUST(root->create_data_property_or_throw(root_name, unfiltered));
  360. return internalize_json_property(vm, root, root_name, reviver.as_function());
  361. }
  362. return unfiltered;
  363. }
  364. Value JSONObject::parse_json_value(VM& vm, JsonValue const& value)
  365. {
  366. if (value.is_object())
  367. return Value(parse_json_object(vm, value.as_object()));
  368. if (value.is_array())
  369. return Value(parse_json_array(vm, value.as_array()));
  370. if (value.is_null())
  371. return js_null();
  372. if (value.is_i32())
  373. return Value(value.as_i32());
  374. if (value.is_number())
  375. return Value(value.to_double(0));
  376. if (value.is_string())
  377. return js_string(vm, value.to_string());
  378. if (value.is_bool())
  379. return Value(static_cast<bool>(value.as_bool()));
  380. VERIFY_NOT_REACHED();
  381. }
  382. Object* JSONObject::parse_json_object(VM& vm, JsonObject const& json_object)
  383. {
  384. auto& realm = *vm.current_realm();
  385. auto* object = Object::create(realm, realm.intrinsics().object_prototype());
  386. json_object.for_each_member([&](auto& key, auto& value) {
  387. object->define_direct_property(key, parse_json_value(vm, value), default_attributes);
  388. });
  389. return object;
  390. }
  391. Array* JSONObject::parse_json_array(VM& vm, JsonArray const& json_array)
  392. {
  393. auto& realm = *vm.current_realm();
  394. auto* array = MUST(Array::create(realm, 0));
  395. size_t index = 0;
  396. json_array.for_each([&](auto& value) {
  397. array->define_direct_property(index++, parse_json_value(vm, value), default_attributes);
  398. });
  399. return array;
  400. }
  401. // 25.5.1.1 InternalizeJSONProperty ( holder, name, reviver ), https://tc39.es/ecma262/#sec-internalizejsonproperty
  402. ThrowCompletionOr<Value> JSONObject::internalize_json_property(VM& vm, Object* holder, PropertyKey const& name, FunctionObject& reviver)
  403. {
  404. auto value = TRY(holder->get(name));
  405. if (value.is_object()) {
  406. auto is_array = TRY(value.is_array(vm));
  407. auto& value_object = value.as_object();
  408. auto process_property = [&](PropertyKey const& key) -> ThrowCompletionOr<void> {
  409. auto element = TRY(internalize_json_property(vm, &value_object, key, reviver));
  410. if (element.is_undefined())
  411. TRY(value_object.internal_delete(key));
  412. else
  413. TRY(value_object.create_data_property(key, element));
  414. return {};
  415. };
  416. if (is_array) {
  417. auto length = TRY(length_of_array_like(vm, value_object));
  418. for (size_t i = 0; i < length; ++i)
  419. TRY(process_property(i));
  420. } else {
  421. auto property_list = TRY(value_object.enumerable_own_property_names(Object::PropertyKind::Key));
  422. for (auto& property_key : property_list)
  423. TRY(process_property(property_key.as_string().string()));
  424. }
  425. }
  426. return TRY(call(vm, reviver, holder, js_string(vm, name.to_string()), value));
  427. }
  428. }