JSONObject.cpp 18 KB

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