JSONObject.cpp 17 KB

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