1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
|
/*
* Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <AK/JsonParser.h>
#include <AK/JsonObject.h>
#include <AK/JsonArray.h>
#include <AK/StringBuilder.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/JSONObject.h>
#include <LibJS/Runtime/Object.h>
namespace JS {
JSONObject::JSONObject()
: Object(interpreter().global_object().object_prototype())
{
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function("stringify", stringify, 3, attr);
define_native_function("parse", parse, 2, attr);
}
JSONObject::~JSONObject()
{
}
Value JSONObject::stringify(Interpreter& interpreter)
{
if (!interpreter.argument_count())
return js_undefined();
auto value = interpreter.argument(0);
auto replacer = interpreter.argument(1);
auto space = interpreter.argument(2);
StringifyState state;
if (replacer.is_object()) {
if (replacer.as_object().is_function()) {
state.replacer_function = &replacer.as_function();
} else if (replacer.is_array()) {
auto& replacer_object = replacer.as_object();
auto replacer_length = length_of_array_like(interpreter, replacer);
if (interpreter.exception())
return {};
Vector<String> list;
for (size_t i = 0; i < replacer_length; ++i) {
auto replacer_value = replacer_object.get(i);
if (interpreter.exception())
return {};
String item;
if (replacer_value.is_string() || replacer_value.is_number()) {
item = replacer_value.to_string(interpreter);
if (interpreter.exception())
return {};
} else if (replacer_value.is_object()) {
auto& value_object = replacer_value.as_object();
if (value_object.is_string_object() || value_object.is_number_object()) {
item = value_object.value_of().to_string(interpreter);
if (interpreter.exception())
return { };
}
}
if (!item.is_null() && !list.contains_slow(item)) {
list.append(item);
}
}
state.property_list = list;
}
}
if (space.is_object()) {
auto& space_obj = space.as_object();
if (space_obj.is_string_object() || space_obj.is_number_object())
space = space_obj.value_of();
}
if (space.is_number()) {
StringBuilder gap_builder;
auto gap_size = min(10, space.as_i32());
for (auto i = 0; i < gap_size; ++i)
gap_builder.append(' ');
state.gap = gap_builder.to_string();
} else if (space.is_string()) {
auto string = space.as_string().string();
if (string.length() <= 10) {
state.gap = string;
} else {
state.gap = string.substring(0, 10);
}
} else {
state.gap = String::empty();
}
auto* wrapper = Object::create_empty(interpreter, interpreter.global_object());
wrapper->define_property(String::empty(), value);
if (interpreter.exception())
return {};
auto result = serialize_json_property(interpreter, state, String::empty(), wrapper);
if (interpreter.exception())
return {};
if (result.is_null())
return js_undefined();
return js_string(interpreter, result);
}
String JSONObject::serialize_json_property(Interpreter& interpreter, StringifyState& state, const PropertyName& key, Object* holder)
{
auto value = holder->get(key);
if (value.is_object()) {
auto to_json = value.as_object().get("toJSON");
if (interpreter.exception())
return {};
if (to_json.is_function()) {
MarkedValueList arguments(interpreter.heap());
arguments.append(js_string(interpreter, key.to_string()));
value = interpreter.call(to_json.as_function(), value, move(arguments));
if (interpreter.exception())
return {};
}
}
if (state.replacer_function) {
MarkedValueList arguments(interpreter.heap());
arguments.values().append(js_string(interpreter, key.to_string()));
arguments.values().append(value);
value = interpreter.call(*state.replacer_function, holder, move(arguments));
if (interpreter.exception())
return {};
}
if (value.is_object()) {
auto& value_object = value.as_object();
if (value_object.is_number_object() || value_object.is_boolean_object() || value_object.is_string_object() || value_object.is_bigint_object())
value = value_object.value_of();
}
if (value.is_null())
return "null";
if (value.is_boolean())
return value.as_bool() ? "true" : "false";
if (value.is_string())
return quote_json_string(value.as_string().string());
if (value.is_number()) {
if (value.is_finite_number())
return value.to_string(interpreter);
return "null";
}
if (value.is_object() && !value.is_function()) {
if (value.is_array())
return serialize_json_array(interpreter, state, static_cast<Array&>(value.as_object()));
return serialize_json_object(interpreter, state, value.as_object());
}
if (value.is_bigint())
interpreter.throw_exception<TypeError>(ErrorType::JsonBigInt);
return {};
}
String JSONObject::serialize_json_object(Interpreter& interpreter, StringifyState& state, Object& object)
{
if (state.seen_objects.contains(&object)) {
interpreter.throw_exception<TypeError>(ErrorType::JsonCircular);
return {};
}
state.seen_objects.set(&object);
String previous_indent = state.indent;
state.indent = String::format("%s%s", state.indent.characters(), state.gap.characters());
Vector<String> property_strings;
auto process_property = [&](const PropertyName& key) {
auto serialized_property_string = serialize_json_property(interpreter, state, key, &object);
if (interpreter.exception())
return;
if (!serialized_property_string.is_null()) {
property_strings.append(String::format(
"%s:%s%s",
quote_json_string(key.to_string()).characters(),
state.gap.is_empty() ? "" : " ",
serialized_property_string.characters()
));
}
};
if (state.property_list.has_value()) {
auto property_list = state.property_list.value();
for (auto& property : property_list) {
process_property(property);
if (interpreter.exception())
return {};
}
} else {
for (auto& entry : object.indexed_properties()) {
auto value_and_attributes = entry.value_and_attributes(&object);
if (!value_and_attributes.attributes.is_enumerable())
continue;
process_property(entry.index());
if (interpreter.exception())
return {};
}
for (auto&[key, metadata] : object.shape().property_table_ordered()) {
if (!metadata.attributes.is_enumerable())
continue;
process_property(key);
if (interpreter.exception())
return {};
}
}
StringBuilder builder;
if (property_strings.is_empty()) {
builder.append("{}");
} else {
bool first = true;
builder.append('{');
if (state.gap.is_empty()) {
for (auto& property_string : property_strings) {
if (!first)
builder.append(',');
first = false;
builder.append(property_string);
}
} else {
builder.append('\n');
builder.append(state.indent);
auto separator = String::format(",\n%s", state.indent.characters());
for (auto& property_string : property_strings) {
if (!first)
builder.append(separator);
first = false;
builder.append(property_string);
}
builder.append('\n');
builder.append(previous_indent);
}
builder.append('}');
}
state.seen_objects.remove(&object);
state.indent = previous_indent;
return builder.to_string();
}
String JSONObject::serialize_json_array(Interpreter& interpreter, StringifyState& state, Object& object)
{
if (state.seen_objects.contains(&object)) {
interpreter.throw_exception<TypeError>(ErrorType::JsonCircular);
return {};
}
state.seen_objects.set(&object);
String previous_indent = state.indent;
state.indent = String::format("%s%s", state.indent.characters(), state.gap.characters());
Vector<String> property_strings;
auto length = length_of_array_like(interpreter, Value(&object));
if (interpreter.exception())
return {};
for (size_t i = 0; i < length; ++i) {
if (interpreter.exception())
return {};
auto serialized_property_string = serialize_json_property(interpreter, state, i, &object);
if (interpreter.exception())
return {};
if (serialized_property_string.is_null()) {
property_strings.append("null");
} else {
property_strings.append(serialized_property_string);
}
}
StringBuilder builder;
if (property_strings.is_empty()) {
builder.append("[]");
} else {
if (state.gap.is_empty()) {
builder.append('[');
bool first = true;
for (auto& property_string : property_strings) {
if (!first)
builder.append(',');
first = false;
builder.append(property_string);
}
builder.append(']');
} else {
builder.append("[\n");
builder.append(state.indent);
auto separator = String::format(",\n%s", state.indent.characters());
bool first = true;
for (auto& property_string : property_strings) {
if (!first)
builder.append(separator);
first = false;
builder.append(property_string);
}
builder.append('\n');
builder.append(previous_indent);
builder.append(']');
}
}
state.seen_objects.remove(&object);
state.indent = previous_indent;
return builder.to_string();
}
String JSONObject::quote_json_string(String string)
{
// FIXME: Handle UTF16
StringBuilder builder;
builder.append('"');
for (auto& ch : string) {
switch (ch) {
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\f':
builder.append("\\f");
break;
case '\r':
builder.append("\\r");
break;
case '"':
builder.append("\\\"");
break;
case '\\':
builder.append("\\\\");
break;
default:
if (ch < 0x20) {
builder.append("\\u%#08x", ch);
} else {
builder.append(ch);
}
}
}
builder.append('"');
return builder.to_string();
}
Value JSONObject::parse(Interpreter& interpreter)
{
if (!interpreter.argument_count())
return js_undefined();
auto string = interpreter.argument(0).to_string(interpreter);
if (interpreter.exception())
return {};
auto reviver = interpreter.argument(1);
auto json = JsonValue::from_string(string);
if (!json.has_value()) {
interpreter.throw_exception<SyntaxError>(ErrorType::JsonMalformed);
return {};
}
Value result = parse_json_value(interpreter, json.value());
if (reviver.is_function()) {
auto* holder_object = Object::create_empty(interpreter, interpreter.global_object());
holder_object->define_property(String::empty(), result);
if (interpreter.exception())
return {};
return internalize_json_property(interpreter, holder_object, String::empty(), reviver.as_function());
}
return result;
}
Value JSONObject::parse_json_value(Interpreter& interpreter, const JsonValue& value)
{
if (value.is_object())
return Value(parse_json_object(interpreter, value.as_object()));
if (value.is_array())
return Value(parse_json_array(interpreter, value.as_array()));
if (value.is_null())
return js_null();
#if !defined(KERNEL)
if (value.is_double())
return Value(value.as_double());
#endif
if (value.is_number())
return Value(value.to_i32(0));
if (value.is_string())
return js_string(interpreter, value.to_string());
if (value.is_bool())
return Value(static_cast<bool>(value.as_bool()));
ASSERT_NOT_REACHED();
}
Object* JSONObject::parse_json_object(Interpreter& interpreter, const JsonObject& json_object)
{
auto* object = Object::create_empty(interpreter, interpreter.global_object());
json_object.for_each_member([&object, &interpreter](String key, JsonValue value) {
object->put(key, parse_json_value(interpreter, value));
});
return object;
}
Array* JSONObject::parse_json_array(Interpreter& interpreter, const JsonArray& json_array)
{
auto* array = Array::create(interpreter.global_object());
size_t index = 0;
json_array.for_each([&array, &interpreter, &index](JsonValue value) {
array->put(index++, parse_json_value(interpreter, value));
});
return array;
}
Value JSONObject::internalize_json_property(Interpreter& interpreter, Object* holder, const PropertyName& name, Function& reviver)
{
auto value = holder->get(name);
if (interpreter.exception())
return {};
if (value.is_object()) {
auto& value_object = value.as_object();
auto process_property = [&](const PropertyName& key) {
auto element = internalize_json_property(interpreter, &value_object, key, reviver);
if (interpreter.exception())
return;
if (element.is_undefined()) {
value_object.delete_property(key);
} else {
value_object.define_property(key, element, default_attributes, false);
}
};
if (value_object.is_array()) {
auto length = length_of_array_like(interpreter, value);
for (size_t i = 0; i < length; ++i) {
process_property(i);
if (interpreter.exception())
return {};
}
} else {
for (auto& entry : value_object.indexed_properties()) {
auto value_and_attributes = entry.value_and_attributes(&value_object);
if (!value_and_attributes.attributes.is_enumerable())
continue;
process_property(entry.index());
if (interpreter.exception())
return {};
}
for (auto& [key, metadata] : value_object.shape().property_table_ordered()) {
if (!metadata.attributes.is_enumerable())
continue;
process_property(key);
if (interpreter.exception())
return {};
}
}
}
MarkedValueList arguments(interpreter.heap());
arguments.values().append(js_string(interpreter, name.to_string()));
arguments.values().append(value);
return interpreter.call(reviver, Value(holder), move(arguments));
}
}
|