JSONObject.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. MUST(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 = TRY_OR_DISCARD(object.enumerable_own_property_names(PropertyKind::Key));
  218. for (auto& property : property_list) {
  219. process_property(property.as_string().string());
  220. if (vm.exception())
  221. return {};
  222. }
  223. }
  224. StringBuilder builder;
  225. if (property_strings.is_empty()) {
  226. builder.append("{}");
  227. } else {
  228. bool first = true;
  229. builder.append('{');
  230. if (state.gap.is_empty()) {
  231. for (auto& property_string : property_strings) {
  232. if (!first)
  233. builder.append(',');
  234. first = false;
  235. builder.append(property_string);
  236. }
  237. } else {
  238. builder.append('\n');
  239. builder.append(state.indent);
  240. auto separator = String::formatted(",\n{}", state.indent);
  241. for (auto& property_string : property_strings) {
  242. if (!first)
  243. builder.append(separator);
  244. first = false;
  245. builder.append(property_string);
  246. }
  247. builder.append('\n');
  248. builder.append(previous_indent);
  249. }
  250. builder.append('}');
  251. }
  252. state.seen_objects.remove(&object);
  253. state.indent = previous_indent;
  254. return builder.to_string();
  255. }
  256. // 25.5.2.5 SerializeJSONArray ( state, value ), https://tc39.es/ecma262/#sec-serializejsonarray
  257. String JSONObject::serialize_json_array(GlobalObject& global_object, StringifyState& state, Object& object)
  258. {
  259. auto& vm = global_object.vm();
  260. if (state.seen_objects.contains(&object)) {
  261. vm.throw_exception<TypeError>(global_object, ErrorType::JsonCircular);
  262. return {};
  263. }
  264. state.seen_objects.set(&object);
  265. String previous_indent = state.indent;
  266. state.indent = String::formatted("{}{}", state.indent, state.gap);
  267. Vector<String> property_strings;
  268. auto length = TRY_OR_DISCARD(length_of_array_like(global_object, object));
  269. // Optimization
  270. property_strings.ensure_capacity(length);
  271. for (size_t i = 0; i < length; ++i) {
  272. if (vm.exception())
  273. return {};
  274. auto serialized_property_string = serialize_json_property(global_object, state, i, &object);
  275. if (vm.exception())
  276. return {};
  277. if (serialized_property_string.is_null()) {
  278. property_strings.append("null");
  279. } else {
  280. property_strings.append(serialized_property_string);
  281. }
  282. }
  283. StringBuilder builder;
  284. if (property_strings.is_empty()) {
  285. builder.append("[]");
  286. } else {
  287. if (state.gap.is_empty()) {
  288. builder.append('[');
  289. bool first = true;
  290. for (auto& property_string : property_strings) {
  291. if (!first)
  292. builder.append(',');
  293. first = false;
  294. builder.append(property_string);
  295. }
  296. builder.append(']');
  297. } else {
  298. builder.append("[\n");
  299. builder.append(state.indent);
  300. auto separator = String::formatted(",\n{}", state.indent);
  301. bool first = true;
  302. for (auto& property_string : property_strings) {
  303. if (!first)
  304. builder.append(separator);
  305. first = false;
  306. builder.append(property_string);
  307. }
  308. builder.append('\n');
  309. builder.append(previous_indent);
  310. builder.append(']');
  311. }
  312. }
  313. state.seen_objects.remove(&object);
  314. state.indent = previous_indent;
  315. return builder.to_string();
  316. }
  317. // 25.5.2.2 QuoteJSONString ( value ), https://tc39.es/ecma262/#sec-quotejsonstring
  318. String JSONObject::quote_json_string(String string)
  319. {
  320. // FIXME: Handle UTF16
  321. StringBuilder builder;
  322. builder.append('"');
  323. auto utf_view = Utf8View(string);
  324. for (auto code_point : utf_view) {
  325. switch (code_point) {
  326. case '\b':
  327. builder.append("\\b");
  328. break;
  329. case '\t':
  330. builder.append("\\t");
  331. break;
  332. case '\n':
  333. builder.append("\\n");
  334. break;
  335. case '\f':
  336. builder.append("\\f");
  337. break;
  338. case '\r':
  339. builder.append("\\r");
  340. break;
  341. case '"':
  342. builder.append("\\\"");
  343. break;
  344. case '\\':
  345. builder.append("\\\\");
  346. break;
  347. default:
  348. if (code_point < 0x20) {
  349. builder.appendff("\\u{:04x}", code_point);
  350. } else {
  351. builder.append_code_point(code_point);
  352. }
  353. }
  354. }
  355. builder.append('"');
  356. return builder.to_string();
  357. }
  358. // 25.5.1 JSON.parse ( text [ , reviver ] ), https://tc39.es/ecma262/#sec-json.parse
  359. JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
  360. {
  361. auto string = vm.argument(0).to_string(global_object);
  362. if (vm.exception())
  363. return {};
  364. auto reviver = vm.argument(1);
  365. auto json = JsonValue::from_string(string);
  366. if (!json.has_value()) {
  367. vm.throw_exception<SyntaxError>(global_object, ErrorType::JsonMalformed);
  368. return {};
  369. }
  370. Value unfiltered = parse_json_value(global_object, json.value());
  371. if (reviver.is_function()) {
  372. auto* root = Object::create(global_object, global_object.object_prototype());
  373. auto root_name = String::empty();
  374. MUST(root->create_data_property_or_throw(root_name, unfiltered));
  375. auto result = internalize_json_property(global_object, root, root_name, reviver.as_function());
  376. if (vm.exception())
  377. return {};
  378. return result;
  379. }
  380. return unfiltered;
  381. }
  382. Value JSONObject::parse_json_value(GlobalObject& global_object, const JsonValue& value)
  383. {
  384. if (value.is_object())
  385. return Value(parse_json_object(global_object, value.as_object()));
  386. if (value.is_array())
  387. return Value(parse_json_array(global_object, value.as_array()));
  388. if (value.is_null())
  389. return js_null();
  390. if (value.is_double())
  391. return Value(value.as_double());
  392. if (value.is_number())
  393. return Value(value.to_i32(0));
  394. if (value.is_string())
  395. return js_string(global_object.heap(), value.to_string());
  396. if (value.is_bool())
  397. return Value(static_cast<bool>(value.as_bool()));
  398. VERIFY_NOT_REACHED();
  399. }
  400. Object* JSONObject::parse_json_object(GlobalObject& global_object, const JsonObject& json_object)
  401. {
  402. auto* object = Object::create(global_object, global_object.object_prototype());
  403. json_object.for_each_member([&](auto& key, auto& value) {
  404. object->define_direct_property(key, parse_json_value(global_object, value), JS::default_attributes);
  405. });
  406. return object;
  407. }
  408. Array* JSONObject::parse_json_array(GlobalObject& global_object, const JsonArray& json_array)
  409. {
  410. auto* array = Array::create(global_object, 0);
  411. size_t index = 0;
  412. json_array.for_each([&](auto& value) {
  413. array->define_direct_property(index++, parse_json_value(global_object, value), JS::default_attributes);
  414. });
  415. return array;
  416. }
  417. // 25.5.1.1 InternalizeJSONProperty ( holder, name, reviver ), https://tc39.es/ecma262/#sec-internalizejsonproperty
  418. Value JSONObject::internalize_json_property(GlobalObject& global_object, Object* holder, PropertyName const& name, FunctionObject& reviver)
  419. {
  420. auto& vm = global_object.vm();
  421. auto value = TRY_OR_DISCARD(holder->get(name));
  422. if (value.is_object()) {
  423. auto is_array = TRY_OR_DISCARD(value.is_array(global_object));
  424. auto& value_object = value.as_object();
  425. auto process_property = [&](const PropertyName& key) -> ThrowCompletionOr<void> {
  426. auto element = internalize_json_property(global_object, &value_object, key, reviver);
  427. if (auto* exception = vm.exception())
  428. return throw_completion(exception->value());
  429. if (element.is_undefined())
  430. TRY(value_object.internal_delete(key));
  431. else
  432. TRY(value_object.create_data_property(key, element));
  433. return {};
  434. };
  435. if (is_array) {
  436. auto length = TRY_OR_DISCARD(length_of_array_like(global_object, value_object));
  437. for (size_t i = 0; i < length; ++i)
  438. TRY_OR_DISCARD(process_property(i));
  439. } else {
  440. auto property_list = TRY_OR_DISCARD(value_object.enumerable_own_property_names(Object::PropertyKind::Key));
  441. for (auto& property_name : property_list)
  442. TRY_OR_DISCARD(process_property(property_name.as_string().string()));
  443. }
  444. }
  445. return TRY_OR_DISCARD(vm.call(reviver, Value(holder), js_string(vm, name.to_string()), value));
  446. }
  447. }