JSONObject.cpp 17 KB

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