JSONObject.cpp 17 KB

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