JSONObject.cpp 17 KB

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