JSONObject.cpp 17 KB

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