JSONObject.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/BigIntObject.h>
  13. #include <LibJS/Runtime/BooleanObject.h>
  14. #include <LibJS/Runtime/Error.h>
  15. #include <LibJS/Runtime/GlobalObject.h>
  16. #include <LibJS/Runtime/JSONObject.h>
  17. #include <LibJS/Runtime/NumberObject.h>
  18. #include <LibJS/Runtime/Object.h>
  19. #include <LibJS/Runtime/StringObject.h>
  20. namespace JS {
  21. JSONObject::JSONObject(GlobalObject& global_object)
  22. : Object(*global_object.object_prototype())
  23. {
  24. }
  25. void JSONObject::initialize(GlobalObject& global_object)
  26. {
  27. auto& vm = this->vm();
  28. Object::initialize(global_object);
  29. u8 attr = Attribute::Writable | Attribute::Configurable;
  30. define_native_function(vm.names.stringify, stringify, 3, attr);
  31. define_native_function(vm.names.parse, parse, 2, attr);
  32. // 25.5.3 JSON [ @@toStringTag ], https://tc39.es/ecma262/#sec-json-@@tostringtag
  33. define_property(vm.well_known_symbol_to_string_tag(), js_string(global_object.heap(), "JSON"), Attribute::Configurable);
  34. }
  35. JSONObject::~JSONObject()
  36. {
  37. }
  38. String JSONObject::stringify_impl(GlobalObject& global_object, Value value, Value replacer, Value space)
  39. {
  40. auto& vm = global_object.vm();
  41. StringifyState state;
  42. if (replacer.is_object()) {
  43. if (replacer.as_object().is_function()) {
  44. state.replacer_function = &replacer.as_function();
  45. } else if (replacer.is_array(global_object)) {
  46. auto& replacer_object = replacer.as_object();
  47. auto replacer_length = length_of_array_like(global_object, replacer_object);
  48. if (vm.exception())
  49. return {};
  50. Vector<String> list;
  51. for (size_t i = 0; i < replacer_length; ++i) {
  52. auto replacer_value = replacer_object.get(i);
  53. if (vm.exception())
  54. return {};
  55. String item;
  56. if (replacer_value.is_string() || replacer_value.is_number()) {
  57. item = replacer_value.to_string(global_object);
  58. if (vm.exception())
  59. return {};
  60. } else if (replacer_value.is_object()) {
  61. auto& value_object = replacer_value.as_object();
  62. if (is<StringObject>(value_object) || is<NumberObject>(value_object)) {
  63. item = value_object.value_of().to_string(global_object);
  64. if (vm.exception())
  65. return {};
  66. }
  67. }
  68. if (!item.is_null() && !list.contains_slow(item)) {
  69. list.append(item);
  70. }
  71. }
  72. state.property_list = list;
  73. }
  74. if (vm.exception())
  75. return {};
  76. }
  77. if (space.is_object()) {
  78. auto& space_obj = space.as_object();
  79. if (is<StringObject>(space_obj) || is<NumberObject>(space_obj))
  80. space = space_obj.value_of();
  81. }
  82. if (space.is_number()) {
  83. StringBuilder gap_builder;
  84. auto gap_size = min(10, space.as_i32());
  85. for (auto i = 0; i < gap_size; ++i)
  86. gap_builder.append(' ');
  87. state.gap = gap_builder.to_string();
  88. } else if (space.is_string()) {
  89. auto string = space.as_string().string();
  90. if (string.length() <= 10) {
  91. state.gap = string;
  92. } else {
  93. state.gap = string.substring(0, 10);
  94. }
  95. } else {
  96. state.gap = String::empty();
  97. }
  98. auto* wrapper = Object::create(global_object, global_object.object_prototype());
  99. wrapper->define_property(String::empty(), value);
  100. if (vm.exception())
  101. return {};
  102. auto result = serialize_json_property(global_object, state, String::empty(), wrapper);
  103. if (vm.exception())
  104. return {};
  105. if (result.is_null())
  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. String JSONObject::serialize_json_property(GlobalObject& global_object, StringifyState& state, const PropertyName& key, Object* holder)
  123. {
  124. auto& vm = global_object.vm();
  125. auto value = holder->get(key);
  126. if (vm.exception())
  127. return {};
  128. if (value.is_object()) {
  129. auto to_json = value.as_object().get(vm.names.toJSON);
  130. if (vm.exception())
  131. return {};
  132. if (to_json.is_function()) {
  133. value = vm.call(to_json.as_function(), value, js_string(vm, key.to_string()));
  134. if (vm.exception())
  135. return {};
  136. }
  137. }
  138. if (state.replacer_function) {
  139. value = vm.call(*state.replacer_function, holder, js_string(vm, key.to_string()), value);
  140. if (vm.exception())
  141. return {};
  142. }
  143. if (value.is_object()) {
  144. auto& value_object = value.as_object();
  145. if (is<NumberObject>(value_object) || is<BooleanObject>(value_object) || is<StringObject>(value_object) || is<BigIntObject>(value_object))
  146. value = value_object.value_of();
  147. }
  148. if (value.is_null())
  149. return "null";
  150. if (value.is_boolean())
  151. return value.as_bool() ? "true" : "false";
  152. if (value.is_string())
  153. return quote_json_string(value.as_string().string());
  154. if (value.is_number()) {
  155. if (value.is_finite_number())
  156. return value.to_string(global_object);
  157. return "null";
  158. }
  159. if (value.is_object() && !value.is_function()) {
  160. if (value.is_array(global_object))
  161. return serialize_json_array(global_object, state, static_cast<Array&>(value.as_object()));
  162. if (vm.exception())
  163. return {};
  164. return serialize_json_object(global_object, state, value.as_object());
  165. }
  166. if (value.is_bigint())
  167. vm.throw_exception<TypeError>(global_object, ErrorType::JsonBigInt);
  168. return {};
  169. }
  170. String JSONObject::serialize_json_object(GlobalObject& global_object, StringifyState& state, Object& object)
  171. {
  172. auto& vm = global_object.vm();
  173. if (state.seen_objects.contains(&object)) {
  174. vm.throw_exception<TypeError>(global_object, ErrorType::JsonCircular);
  175. return {};
  176. }
  177. state.seen_objects.set(&object);
  178. String previous_indent = state.indent;
  179. state.indent = String::formatted("{}{}", state.indent, state.gap);
  180. Vector<String> property_strings;
  181. auto process_property = [&](const PropertyName& key) {
  182. if (key.is_symbol())
  183. return;
  184. auto serialized_property_string = serialize_json_property(global_object, state, key, &object);
  185. if (vm.exception())
  186. return;
  187. if (!serialized_property_string.is_null()) {
  188. property_strings.append(String::formatted(
  189. "{}:{}{}",
  190. quote_json_string(key.to_string()),
  191. state.gap.is_empty() ? "" : " ",
  192. serialized_property_string));
  193. }
  194. };
  195. if (state.property_list.has_value()) {
  196. auto property_list = state.property_list.value();
  197. for (auto& property : property_list) {
  198. process_property(property);
  199. if (vm.exception())
  200. return {};
  201. }
  202. } else {
  203. for (auto& entry : object.indexed_properties()) {
  204. auto value_and_attributes = entry.value_and_attributes(&object);
  205. if (!value_and_attributes.attributes.is_enumerable())
  206. continue;
  207. process_property(entry.index());
  208. if (vm.exception())
  209. return {};
  210. }
  211. for (auto& [key, metadata] : object.shape().property_table_ordered()) {
  212. if (!metadata.attributes.is_enumerable())
  213. continue;
  214. process_property(key);
  215. if (vm.exception())
  216. return {};
  217. }
  218. }
  219. StringBuilder builder;
  220. if (property_strings.is_empty()) {
  221. builder.append("{}");
  222. } else {
  223. bool first = true;
  224. builder.append('{');
  225. if (state.gap.is_empty()) {
  226. for (auto& property_string : property_strings) {
  227. if (!first)
  228. builder.append(',');
  229. first = false;
  230. builder.append(property_string);
  231. }
  232. } else {
  233. builder.append('\n');
  234. builder.append(state.indent);
  235. auto separator = String::formatted(",\n{}", state.indent);
  236. for (auto& property_string : property_strings) {
  237. if (!first)
  238. builder.append(separator);
  239. first = false;
  240. builder.append(property_string);
  241. }
  242. builder.append('\n');
  243. builder.append(previous_indent);
  244. }
  245. builder.append('}');
  246. }
  247. state.seen_objects.remove(&object);
  248. state.indent = previous_indent;
  249. return builder.to_string();
  250. }
  251. String JSONObject::serialize_json_array(GlobalObject& global_object, StringifyState& state, Object& object)
  252. {
  253. auto& vm = global_object.vm();
  254. if (state.seen_objects.contains(&object)) {
  255. vm.throw_exception<TypeError>(global_object, ErrorType::JsonCircular);
  256. return {};
  257. }
  258. state.seen_objects.set(&object);
  259. String previous_indent = state.indent;
  260. state.indent = String::formatted("{}{}", state.indent, state.gap);
  261. Vector<String> property_strings;
  262. auto length = length_of_array_like(global_object, object);
  263. if (vm.exception())
  264. return {};
  265. for (size_t i = 0; i < length; ++i) {
  266. if (vm.exception())
  267. return {};
  268. auto serialized_property_string = serialize_json_property(global_object, state, i, &object);
  269. if (vm.exception())
  270. return {};
  271. if (serialized_property_string.is_null()) {
  272. property_strings.append("null");
  273. } else {
  274. property_strings.append(serialized_property_string);
  275. }
  276. }
  277. StringBuilder builder;
  278. if (property_strings.is_empty()) {
  279. builder.append("[]");
  280. } else {
  281. if (state.gap.is_empty()) {
  282. builder.append('[');
  283. bool first = true;
  284. for (auto& property_string : property_strings) {
  285. if (!first)
  286. builder.append(',');
  287. first = false;
  288. builder.append(property_string);
  289. }
  290. builder.append(']');
  291. } else {
  292. builder.append("[\n");
  293. builder.append(state.indent);
  294. auto separator = String::formatted(",\n{}", state.indent);
  295. bool first = true;
  296. for (auto& property_string : property_strings) {
  297. if (!first)
  298. builder.append(separator);
  299. first = false;
  300. builder.append(property_string);
  301. }
  302. builder.append('\n');
  303. builder.append(previous_indent);
  304. builder.append(']');
  305. }
  306. }
  307. state.seen_objects.remove(&object);
  308. state.indent = previous_indent;
  309. return builder.to_string();
  310. }
  311. String JSONObject::quote_json_string(String string)
  312. {
  313. // FIXME: Handle UTF16
  314. StringBuilder builder;
  315. builder.append('"');
  316. for (auto& ch : string) {
  317. switch (ch) {
  318. case '\b':
  319. builder.append("\\b");
  320. break;
  321. case '\t':
  322. builder.append("\\t");
  323. break;
  324. case '\n':
  325. builder.append("\\n");
  326. break;
  327. case '\f':
  328. builder.append("\\f");
  329. break;
  330. case '\r':
  331. builder.append("\\r");
  332. break;
  333. case '"':
  334. builder.append("\\\"");
  335. break;
  336. case '\\':
  337. builder.append("\\\\");
  338. break;
  339. default:
  340. if (ch < 0x20) {
  341. builder.appendff("\\u{:04x}", ch);
  342. } else {
  343. builder.append(ch);
  344. }
  345. }
  346. }
  347. builder.append('"');
  348. return builder.to_string();
  349. }
  350. // 25.5.1 JSON.parse ( text [ , reviver ] ), https://tc39.es/ecma262/#sec-json.parse
  351. JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
  352. {
  353. if (!vm.argument_count())
  354. return js_undefined();
  355. auto string = vm.argument(0).to_string(global_object);
  356. if (vm.exception())
  357. return {};
  358. auto reviver = vm.argument(1);
  359. auto json = JsonValue::from_string(string);
  360. if (!json.has_value()) {
  361. vm.throw_exception<SyntaxError>(global_object, ErrorType::JsonMalformed);
  362. return {};
  363. }
  364. Value result = parse_json_value(global_object, json.value());
  365. if (reviver.is_function()) {
  366. auto* root = Object::create(global_object, global_object.object_prototype());
  367. auto root_name = String::empty();
  368. root->define_property(root_name, result);
  369. if (vm.exception())
  370. return {};
  371. return internalize_json_property(global_object, root, root_name, reviver.as_function());
  372. }
  373. return result;
  374. }
  375. Value JSONObject::parse_json_value(GlobalObject& global_object, const JsonValue& value)
  376. {
  377. if (value.is_object())
  378. return Value(parse_json_object(global_object, value.as_object()));
  379. if (value.is_array())
  380. return Value(parse_json_array(global_object, value.as_array()));
  381. if (value.is_null())
  382. return js_null();
  383. if (value.is_double())
  384. return Value(value.as_double());
  385. if (value.is_number())
  386. return Value(value.to_i32(0));
  387. if (value.is_string())
  388. return js_string(global_object.heap(), value.to_string());
  389. if (value.is_bool())
  390. return Value(static_cast<bool>(value.as_bool()));
  391. VERIFY_NOT_REACHED();
  392. }
  393. Object* JSONObject::parse_json_object(GlobalObject& global_object, const JsonObject& json_object)
  394. {
  395. auto* object = Object::create(global_object, global_object.object_prototype());
  396. json_object.for_each_member([&](auto& key, auto& value) {
  397. object->define_property(key, parse_json_value(global_object, value));
  398. });
  399. return object;
  400. }
  401. Array* JSONObject::parse_json_array(GlobalObject& global_object, const JsonArray& json_array)
  402. {
  403. auto* array = Array::create(global_object);
  404. size_t index = 0;
  405. json_array.for_each([&](auto& value) {
  406. array->define_property(index++, parse_json_value(global_object, value));
  407. });
  408. return array;
  409. }
  410. // 25.5.1.1 InternalizeJSONProperty ( holder, name, reviver ), https://tc39.es/ecma262/#sec-internalizejsonproperty
  411. Value JSONObject::internalize_json_property(GlobalObject& global_object, Object* holder, const PropertyName& name, Function& reviver)
  412. {
  413. auto& vm = global_object.vm();
  414. auto value = holder->get(name);
  415. if (vm.exception())
  416. return {};
  417. if (value.is_object()) {
  418. auto& value_object = value.as_object();
  419. auto process_property = [&](const PropertyName& key) {
  420. auto element = internalize_json_property(global_object, &value_object, key, reviver);
  421. if (vm.exception())
  422. return;
  423. if (element.is_undefined()) {
  424. value_object.delete_property(key);
  425. } else {
  426. value_object.define_property(key, element, default_attributes, false);
  427. }
  428. };
  429. if (value_object.is_array()) {
  430. auto length = length_of_array_like(global_object, value_object);
  431. for (size_t i = 0; i < length; ++i) {
  432. process_property(i);
  433. if (vm.exception())
  434. return {};
  435. }
  436. } else {
  437. for (auto& entry : value_object.indexed_properties()) {
  438. auto value_and_attributes = entry.value_and_attributes(&value_object);
  439. if (!value_and_attributes.attributes.is_enumerable())
  440. continue;
  441. process_property(entry.index());
  442. if (vm.exception())
  443. return {};
  444. }
  445. for (auto& [key, metadata] : value_object.shape().property_table_ordered()) {
  446. if (!metadata.attributes.is_enumerable())
  447. continue;
  448. process_property(key);
  449. if (vm.exception())
  450. return {};
  451. }
  452. }
  453. }
  454. return vm.call(reviver, Value(holder), js_string(vm, name.to_string()), value);
  455. }
  456. }