JSONObject.cpp 17 KB

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