JSONObject.cpp 18 KB

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