JSONObject.cpp 16 KB

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