JSONObject.cpp 17 KB

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