JSONObject.cpp 16 KB

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