JSONObject.cpp 17 KB

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