JSONObject.cpp 18 KB

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