JSONObject.cpp 17 KB

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