JSONObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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.global_object().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(vm.names.stringify, stringify, 3, attr);
  35. define_native_function(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(GlobalObject& global_object, Value value, Value replacer, Value space)
  41. {
  42. auto& realm = *global_object.associated_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(global_object));
  49. if (is_array) {
  50. auto& replacer_object = replacer.as_object();
  51. auto replacer_length = TRY(length_of_array_like(global_object, 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(global_object));
  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(global_object));
  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(global_object));
  77. else if (is<StringObject>(space_object))
  78. space = TRY(space.to_primitive_string(global_object));
  79. }
  80. if (space.is_number()) {
  81. auto space_mv = MUST(space.to_integer_or_infinity(global_object));
  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, global_object.object_prototype());
  94. MUST(wrapper->create_data_property_or_throw(String::empty(), value));
  95. return serialize_json_property(global_object, 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(global_object, 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(GlobalObject& global_object, StringifyState& state, PropertyKey const& key, Object* holder)
  112. {
  113. auto& vm = global_object.vm();
  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(global_object, 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(global_object, 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(global_object, *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(global_object));
  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(global_object));
  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(global_object));
  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>(global_object, 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(global_object));
  180. // b. If isArray is true, return ? SerializeJSONArray(state, value).
  181. if (is_array)
  182. return serialize_json_array(global_object, state, static_cast<Array&>(value.as_object()));
  183. // c. Return ? SerializeJSONObject(state, value).
  184. return serialize_json_object(global_object, 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(GlobalObject& global_object, StringifyState& state, Object& object)
  191. {
  192. auto& vm = global_object.vm();
  193. if (state.seen_objects.contains(&object))
  194. return vm.throw_completion<TypeError>(global_object, ErrorType::JsonCircular);
  195. state.seen_objects.set(&object);
  196. String previous_indent = state.indent;
  197. state.indent = String::formatted("{}{}", state.indent, state.gap);
  198. Vector<String> 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(global_object, state, key, &object));
  203. if (!serialized_property_string.is_null()) {
  204. property_strings.append(String::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().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 = String::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_string();
  252. }
  253. // 25.5.2.5 SerializeJSONArray ( state, value ), https://tc39.es/ecma262/#sec-serializejsonarray
  254. ThrowCompletionOr<String> JSONObject::serialize_json_array(GlobalObject& global_object, StringifyState& state, Object& object)
  255. {
  256. auto& vm = global_object.vm();
  257. if (state.seen_objects.contains(&object))
  258. return vm.throw_completion<TypeError>(global_object, ErrorType::JsonCircular);
  259. state.seen_objects.set(&object);
  260. String previous_indent = state.indent;
  261. state.indent = String::formatted("{}{}", state.indent, state.gap);
  262. Vector<String> property_strings;
  263. auto length = TRY(length_of_array_like(global_object, 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(global_object, state, i, &object));
  268. if (serialized_property_string.is_null()) {
  269. property_strings.append("null"sv);
  270. } else {
  271. property_strings.append(serialized_property_string);
  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 = String::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_string();
  307. }
  308. // 25.5.2.2 QuoteJSONString ( value ), https://tc39.es/ecma262/#sec-quotejsonstring
  309. String JSONObject::quote_json_string(String string)
  310. {
  311. StringBuilder builder;
  312. builder.append('"');
  313. auto utf_view = Utf8View(string);
  314. for (auto code_point : utf_view) {
  315. switch (code_point) {
  316. case '\b':
  317. builder.append("\\b"sv);
  318. break;
  319. case '\t':
  320. builder.append("\\t"sv);
  321. break;
  322. case '\n':
  323. builder.append("\\n"sv);
  324. break;
  325. case '\f':
  326. builder.append("\\f"sv);
  327. break;
  328. case '\r':
  329. builder.append("\\r"sv);
  330. break;
  331. case '"':
  332. builder.append("\\\""sv);
  333. break;
  334. case '\\':
  335. builder.append("\\\\"sv);
  336. break;
  337. default:
  338. if (code_point < 0x20 || Utf16View::is_high_surrogate(code_point) || Utf16View::is_low_surrogate(code_point)) {
  339. builder.appendff("\\u{:04x}", code_point);
  340. } else {
  341. builder.append_code_point(code_point);
  342. }
  343. }
  344. }
  345. builder.append('"');
  346. return builder.to_string();
  347. }
  348. // 25.5.1 JSON.parse ( text [ , reviver ] ), https://tc39.es/ecma262/#sec-json.parse
  349. JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
  350. {
  351. auto& realm = *global_object.associated_realm();
  352. auto string = TRY(vm.argument(0).to_string(global_object));
  353. auto reviver = vm.argument(1);
  354. auto json = JsonValue::from_string(string);
  355. if (json.is_error())
  356. return vm.throw_completion<SyntaxError>(global_object, ErrorType::JsonMalformed);
  357. Value unfiltered = parse_json_value(global_object, json.value());
  358. if (reviver.is_function()) {
  359. auto* root = Object::create(realm, global_object.object_prototype());
  360. auto root_name = String::empty();
  361. MUST(root->create_data_property_or_throw(root_name, unfiltered));
  362. return internalize_json_property(global_object, root, root_name, reviver.as_function());
  363. }
  364. return unfiltered;
  365. }
  366. Value JSONObject::parse_json_value(GlobalObject& global_object, JsonValue const& value)
  367. {
  368. if (value.is_object())
  369. return Value(parse_json_object(global_object, value.as_object()));
  370. if (value.is_array())
  371. return Value(parse_json_array(global_object, value.as_array()));
  372. if (value.is_null())
  373. return js_null();
  374. if (value.is_double())
  375. return Value(value.as_double());
  376. if (value.is_number())
  377. return Value(value.to_i32(0));
  378. if (value.is_string())
  379. return js_string(global_object.heap(), value.to_string());
  380. if (value.is_bool())
  381. return Value(static_cast<bool>(value.as_bool()));
  382. VERIFY_NOT_REACHED();
  383. }
  384. Object* JSONObject::parse_json_object(GlobalObject& global_object, JsonObject const& json_object)
  385. {
  386. auto& realm = *global_object.associated_realm();
  387. auto* object = Object::create(realm, global_object.object_prototype());
  388. json_object.for_each_member([&](auto& key, auto& value) {
  389. object->define_direct_property(key, parse_json_value(global_object, value), default_attributes);
  390. });
  391. return object;
  392. }
  393. Array* JSONObject::parse_json_array(GlobalObject& global_object, JsonArray const& json_array)
  394. {
  395. auto& realm = *global_object.associated_realm();
  396. auto* array = MUST(Array::create(realm, 0));
  397. size_t index = 0;
  398. json_array.for_each([&](auto& value) {
  399. array->define_direct_property(index++, parse_json_value(global_object, value), default_attributes);
  400. });
  401. return array;
  402. }
  403. // 25.5.1.1 InternalizeJSONProperty ( holder, name, reviver ), https://tc39.es/ecma262/#sec-internalizejsonproperty
  404. ThrowCompletionOr<Value> JSONObject::internalize_json_property(GlobalObject& global_object, Object* holder, PropertyKey const& name, FunctionObject& reviver)
  405. {
  406. auto& vm = global_object.vm();
  407. auto value = TRY(holder->get(name));
  408. if (value.is_object()) {
  409. auto is_array = TRY(value.is_array(global_object));
  410. auto& value_object = value.as_object();
  411. auto process_property = [&](PropertyKey const& key) -> ThrowCompletionOr<void> {
  412. auto element = TRY(internalize_json_property(global_object, &value_object, key, reviver));
  413. if (element.is_undefined())
  414. TRY(value_object.internal_delete(key));
  415. else
  416. TRY(value_object.create_data_property(key, element));
  417. return {};
  418. };
  419. if (is_array) {
  420. auto length = TRY(length_of_array_like(global_object, value_object));
  421. for (size_t i = 0; i < length; ++i)
  422. TRY(process_property(i));
  423. } else {
  424. auto property_list = TRY(value_object.enumerable_own_property_names(Object::PropertyKind::Key));
  425. for (auto& property_key : property_list)
  426. TRY(process_property(property_key.as_string().string()));
  427. }
  428. }
  429. return TRY(call(global_object, reviver, holder, js_string(vm, name.to_string()), value));
  430. }
  431. }