JSONObject.cpp 18 KB

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