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