JSONObject.cpp 18 KB

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