JSONObject.cpp 17 KB

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