JSONObject.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/JsonArray.h>
  27. #include <AK/JsonObject.h>
  28. #include <AK/JsonParser.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibJS/Runtime/Array.h>
  31. #include <LibJS/Runtime/Error.h>
  32. #include <LibJS/Runtime/GlobalObject.h>
  33. #include <LibJS/Runtime/JSONObject.h>
  34. #include <LibJS/Runtime/Object.h>
  35. namespace JS {
  36. JSONObject::JSONObject(GlobalObject& global_object)
  37. : Object(*global_object.object_prototype())
  38. {
  39. }
  40. void JSONObject::initialize(GlobalObject& global_object)
  41. {
  42. Object::initialize(global_object);
  43. u8 attr = Attribute::Writable | Attribute::Configurable;
  44. define_native_function("stringify", stringify, 3, attr);
  45. define_native_function("parse", parse, 2, attr);
  46. define_property(global_object.vm().well_known_symbol_to_string_tag(), js_string(global_object.heap(), "JSON"), Attribute::Configurable);
  47. }
  48. JSONObject::~JSONObject()
  49. {
  50. }
  51. String JSONObject::stringify_impl(GlobalObject& global_object, Value value, Value replacer, Value space)
  52. {
  53. auto& vm = global_object.vm();
  54. StringifyState state;
  55. if (replacer.is_object()) {
  56. if (replacer.as_object().is_function()) {
  57. state.replacer_function = &replacer.as_function();
  58. } else if (replacer.is_array()) {
  59. auto& replacer_object = replacer.as_object();
  60. auto replacer_length = length_of_array_like(global_object, replacer);
  61. if (vm.exception())
  62. return {};
  63. Vector<String> list;
  64. for (size_t i = 0; i < replacer_length; ++i) {
  65. auto replacer_value = replacer_object.get(i);
  66. if (vm.exception())
  67. return {};
  68. String item;
  69. if (replacer_value.is_string() || replacer_value.is_number()) {
  70. item = replacer_value.to_string(global_object);
  71. if (vm.exception())
  72. return {};
  73. } else if (replacer_value.is_object()) {
  74. auto& value_object = replacer_value.as_object();
  75. if (value_object.is_string_object() || value_object.is_number_object()) {
  76. item = value_object.value_of().to_string(global_object);
  77. if (vm.exception())
  78. return {};
  79. }
  80. }
  81. if (!item.is_null() && !list.contains_slow(item)) {
  82. list.append(item);
  83. }
  84. }
  85. state.property_list = list;
  86. }
  87. }
  88. if (space.is_object()) {
  89. auto& space_obj = space.as_object();
  90. if (space_obj.is_string_object() || space_obj.is_number_object())
  91. space = space_obj.value_of();
  92. }
  93. if (space.is_number()) {
  94. StringBuilder gap_builder;
  95. auto gap_size = min(10, space.as_i32());
  96. for (auto i = 0; i < gap_size; ++i)
  97. gap_builder.append(' ');
  98. state.gap = gap_builder.to_string();
  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. }
  106. } else {
  107. state.gap = String::empty();
  108. }
  109. auto* wrapper = Object::create_empty(global_object);
  110. wrapper->define_property(String::empty(), value);
  111. if (vm.exception())
  112. return {};
  113. auto result = serialize_json_property(global_object, state, String::empty(), wrapper);
  114. if (vm.exception())
  115. return {};
  116. if (result.is_null())
  117. return {};
  118. return result;
  119. }
  120. JS_DEFINE_NATIVE_FUNCTION(JSONObject::stringify)
  121. {
  122. if (!vm.argument_count())
  123. return js_undefined();
  124. auto value = vm.argument(0);
  125. auto replacer = vm.argument(1);
  126. auto space = vm.argument(2);
  127. auto string = stringify_impl(global_object, value, replacer, space);
  128. if (string.is_null())
  129. return js_undefined();
  130. return js_string(vm, string);
  131. }
  132. String JSONObject::serialize_json_property(GlobalObject& global_object, StringifyState& state, const PropertyName& key, Object* holder)
  133. {
  134. auto& vm = global_object.vm();
  135. auto value = holder->get(key);
  136. if (vm.exception())
  137. return {};
  138. if (value.is_object()) {
  139. auto to_json = value.as_object().get("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 (value_object.is_number_object() || value_object.is_boolean_object() || value_object.is_string_object() || value_object.is_bigint_object())
  156. value = value_object.value_of();
  157. }
  158. if (value.is_null())
  159. return "null";
  160. if (value.is_boolean())
  161. return value.as_bool() ? "true" : "false";
  162. if (value.is_string())
  163. return quote_json_string(value.as_string().string());
  164. if (value.is_number()) {
  165. if (value.is_finite_number())
  166. return value.to_string(global_object);
  167. return "null";
  168. }
  169. if (value.is_object() && !value.is_function()) {
  170. if (value.is_array())
  171. return serialize_json_array(global_object, state, static_cast<Array&>(value.as_object()));
  172. return serialize_json_object(global_object, state, value.as_object());
  173. }
  174. if (value.is_bigint())
  175. vm.throw_exception<TypeError>(global_object, ErrorType::JsonBigInt);
  176. return {};
  177. }
  178. String JSONObject::serialize_json_object(GlobalObject& global_object, StringifyState& state, Object& object)
  179. {
  180. auto& vm = global_object.vm();
  181. if (state.seen_objects.contains(&object)) {
  182. vm.throw_exception<TypeError>(global_object, ErrorType::JsonCircular);
  183. return {};
  184. }
  185. state.seen_objects.set(&object);
  186. String previous_indent = state.indent;
  187. state.indent = String::format("%s%s", state.indent.characters(), state.gap.characters());
  188. Vector<String> property_strings;
  189. auto process_property = [&](const PropertyName& key) {
  190. auto serialized_property_string = serialize_json_property(global_object, state, key, &object);
  191. if (vm.exception())
  192. return;
  193. if (!serialized_property_string.is_null()) {
  194. property_strings.append(String::format(
  195. "%s:%s%s",
  196. quote_json_string(key.to_string()).characters(),
  197. state.gap.is_empty() ? "" : " ",
  198. serialized_property_string.characters()));
  199. }
  200. };
  201. if (state.property_list.has_value()) {
  202. auto property_list = state.property_list.value();
  203. for (auto& property : property_list) {
  204. process_property(property);
  205. if (vm.exception())
  206. return {};
  207. }
  208. } else {
  209. for (auto& entry : object.indexed_properties()) {
  210. auto value_and_attributes = entry.value_and_attributes(&object);
  211. if (!value_and_attributes.attributes.is_enumerable())
  212. continue;
  213. process_property(entry.index());
  214. if (vm.exception())
  215. return {};
  216. }
  217. for (auto& [key, metadata] : object.shape().property_table_ordered()) {
  218. if (!metadata.attributes.is_enumerable())
  219. continue;
  220. process_property(key);
  221. if (vm.exception())
  222. return {};
  223. }
  224. }
  225. StringBuilder builder;
  226. if (property_strings.is_empty()) {
  227. builder.append("{}");
  228. } else {
  229. bool first = true;
  230. builder.append('{');
  231. if (state.gap.is_empty()) {
  232. for (auto& property_string : property_strings) {
  233. if (!first)
  234. builder.append(',');
  235. first = false;
  236. builder.append(property_string);
  237. }
  238. } else {
  239. builder.append('\n');
  240. builder.append(state.indent);
  241. auto separator = String::format(",\n%s", state.indent.characters());
  242. for (auto& property_string : property_strings) {
  243. if (!first)
  244. builder.append(separator);
  245. first = false;
  246. builder.append(property_string);
  247. }
  248. builder.append('\n');
  249. builder.append(previous_indent);
  250. }
  251. builder.append('}');
  252. }
  253. state.seen_objects.remove(&object);
  254. state.indent = previous_indent;
  255. return builder.to_string();
  256. }
  257. String JSONObject::serialize_json_array(GlobalObject& global_object, StringifyState& state, Object& object)
  258. {
  259. auto& vm = global_object.vm();
  260. if (state.seen_objects.contains(&object)) {
  261. vm.throw_exception<TypeError>(global_object, ErrorType::JsonCircular);
  262. return {};
  263. }
  264. state.seen_objects.set(&object);
  265. String previous_indent = state.indent;
  266. state.indent = String::format("%s%s", state.indent.characters(), state.gap.characters());
  267. Vector<String> property_strings;
  268. auto length = length_of_array_like(global_object, Value(&object));
  269. if (vm.exception())
  270. return {};
  271. for (size_t i = 0; i < length; ++i) {
  272. if (vm.exception())
  273. return {};
  274. auto serialized_property_string = serialize_json_property(global_object, state, i, &object);
  275. if (vm.exception())
  276. return {};
  277. if (serialized_property_string.is_null()) {
  278. property_strings.append("null");
  279. } else {
  280. property_strings.append(serialized_property_string);
  281. }
  282. }
  283. StringBuilder builder;
  284. if (property_strings.is_empty()) {
  285. builder.append("[]");
  286. } else {
  287. if (state.gap.is_empty()) {
  288. builder.append('[');
  289. bool first = true;
  290. for (auto& property_string : property_strings) {
  291. if (!first)
  292. builder.append(',');
  293. first = false;
  294. builder.append(property_string);
  295. }
  296. builder.append(']');
  297. } else {
  298. builder.append("[\n");
  299. builder.append(state.indent);
  300. auto separator = String::format(",\n%s", state.indent.characters());
  301. bool first = true;
  302. for (auto& property_string : property_strings) {
  303. if (!first)
  304. builder.append(separator);
  305. first = false;
  306. builder.append(property_string);
  307. }
  308. builder.append('\n');
  309. builder.append(previous_indent);
  310. builder.append(']');
  311. }
  312. }
  313. state.seen_objects.remove(&object);
  314. state.indent = previous_indent;
  315. return builder.to_string();
  316. }
  317. String JSONObject::quote_json_string(String string)
  318. {
  319. // FIXME: Handle UTF16
  320. StringBuilder builder;
  321. builder.append('"');
  322. for (auto& ch : string) {
  323. switch (ch) {
  324. case '\b':
  325. builder.append("\\b");
  326. break;
  327. case '\t':
  328. builder.append("\\t");
  329. break;
  330. case '\n':
  331. builder.append("\\n");
  332. break;
  333. case '\f':
  334. builder.append("\\f");
  335. break;
  336. case '\r':
  337. builder.append("\\r");
  338. break;
  339. case '"':
  340. builder.append("\\\"");
  341. break;
  342. case '\\':
  343. builder.append("\\\\");
  344. break;
  345. default:
  346. if (ch < 0x20) {
  347. builder.append("\\u%#08x", ch);
  348. } else {
  349. builder.append(ch);
  350. }
  351. }
  352. }
  353. builder.append('"');
  354. return builder.to_string();
  355. }
  356. JS_DEFINE_NATIVE_FUNCTION(JSONObject::parse)
  357. {
  358. if (!vm.argument_count())
  359. return js_undefined();
  360. auto string = vm.argument(0).to_string(global_object);
  361. if (vm.exception())
  362. return {};
  363. auto reviver = vm.argument(1);
  364. auto json = JsonValue::from_string(string);
  365. if (!json.has_value()) {
  366. vm.throw_exception<SyntaxError>(global_object, ErrorType::JsonMalformed);
  367. return {};
  368. }
  369. Value result = parse_json_value(global_object, json.value());
  370. if (reviver.is_function()) {
  371. auto* holder_object = Object::create_empty(global_object);
  372. holder_object->define_property(String::empty(), result);
  373. if (vm.exception())
  374. return {};
  375. return internalize_json_property(global_object, holder_object, String::empty(), reviver.as_function());
  376. }
  377. return result;
  378. }
  379. Value JSONObject::parse_json_value(GlobalObject& global_object, const JsonValue& value)
  380. {
  381. if (value.is_object())
  382. return Value(parse_json_object(global_object, value.as_object()));
  383. if (value.is_array())
  384. return Value(parse_json_array(global_object, value.as_array()));
  385. if (value.is_null())
  386. return js_null();
  387. #if !defined(KERNEL)
  388. if (value.is_double())
  389. return Value(value.as_double());
  390. #endif
  391. if (value.is_number())
  392. return Value(value.to_i32(0));
  393. if (value.is_string())
  394. return js_string(global_object.heap(), value.to_string());
  395. if (value.is_bool())
  396. return Value(static_cast<bool>(value.as_bool()));
  397. ASSERT_NOT_REACHED();
  398. }
  399. Object* JSONObject::parse_json_object(GlobalObject& global_object, const JsonObject& json_object)
  400. {
  401. auto* object = Object::create_empty(global_object);
  402. json_object.for_each_member([&](auto& key, auto& value) {
  403. object->define_property(key, parse_json_value(global_object, value));
  404. });
  405. return object;
  406. }
  407. Array* JSONObject::parse_json_array(GlobalObject& global_object, const JsonArray& json_array)
  408. {
  409. auto* array = Array::create(global_object);
  410. size_t index = 0;
  411. json_array.for_each([&](auto& value) {
  412. array->define_property(index++, parse_json_value(global_object, value));
  413. });
  414. return array;
  415. }
  416. Value JSONObject::internalize_json_property(GlobalObject& global_object, Object* holder, const PropertyName& name, Function& reviver)
  417. {
  418. auto& vm = global_object.vm();
  419. auto value = holder->get(name);
  420. if (vm.exception())
  421. return {};
  422. if (value.is_object()) {
  423. auto& value_object = value.as_object();
  424. auto process_property = [&](const PropertyName& key) {
  425. auto element = internalize_json_property(global_object, &value_object, key, reviver);
  426. if (vm.exception())
  427. return;
  428. if (element.is_undefined()) {
  429. value_object.delete_property(key);
  430. } else {
  431. value_object.define_property(key, element, default_attributes, false);
  432. }
  433. };
  434. if (value_object.is_array()) {
  435. auto length = length_of_array_like(global_object, value);
  436. for (size_t i = 0; i < length; ++i) {
  437. process_property(i);
  438. if (vm.exception())
  439. return {};
  440. }
  441. } else {
  442. for (auto& entry : value_object.indexed_properties()) {
  443. auto value_and_attributes = entry.value_and_attributes(&value_object);
  444. if (!value_and_attributes.attributes.is_enumerable())
  445. continue;
  446. process_property(entry.index());
  447. if (vm.exception())
  448. return {};
  449. }
  450. for (auto& [key, metadata] : value_object.shape().property_table_ordered()) {
  451. if (!metadata.attributes.is_enumerable())
  452. continue;
  453. process_property(key);
  454. if (vm.exception())
  455. return {};
  456. }
  457. }
  458. }
  459. return vm.call(reviver, Value(holder), js_string(vm, name.to_string()), value);
  460. }
  461. }