JSONObject.cpp 16 KB

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