JSONObject.cpp 17 KB

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