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