-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonParser.java
More file actions
448 lines (421 loc) · 16.3 KB
/
JsonParser.java
File metadata and controls
448 lines (421 loc) · 16.3 KB
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
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.sandbox.internal.util.json;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import jdk.sandbox.java.util.json.JsonArray;
import jdk.sandbox.java.util.json.JsonObject;
import jdk.sandbox.java.util.json.JsonParseException;
import jdk.sandbox.java.util.json.JsonString;
import jdk.sandbox.java.util.json.JsonValue;
/**
* Parses a JSON Document char[] into a tree of JsonValues. JsonObject and JsonArray
* nodes create their data structures which maintain the connection to children.
* JsonNumber and JsonString contain only a start and end offset, which
* are used to lazily procure their underlying value/string on demand. Singletons
* are used for JsonBoolean and JsonNull.
*/
public final class JsonParser {
// Access to the underlying JSON contents
private final char[] doc;
// Lazily initialized for member names with escape sequences
private final Supplier<StringBuilder> sb = StableValue.supplier(this::initSb);
// Current offset during parsing
private int offset;
// For exception message on failure
private int line;
private int lineStart;
public JsonParser(char[] doc) {
this.doc = doc;
}
// Parses the lone JsonValue root
public JsonValue parseRoot() {
JsonValue root = parseValue();
if (hasInput()) {
throw failure("Additional value(s) were found after the JSON Value");
}
return root;
}
/*
* Parse any one of the JSON value types: object, array, number, string,
* true, false, or null.
* JSON-text = ws value ws
* See https://datatracker.ietf.org/doc/html/rfc8259#section-3
*/
private JsonValue parseValue() {
skipWhitespaces();
if (!hasInput()) {
throw failure("Expected a JSON Object, Array, String, Number, Boolean, or Null");
}
var val = switch (doc[offset]) {
case '{' -> parseObject();
case '[' -> parseArray();
case '"' -> parseString();
case 't' -> parseTrue();
case 'f' -> parseFalse();
case 'n' -> parseNull();
// While JSON Number does not support leading '+', '.', or 'e'
// we still accept, so that we can provide a better error message
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+', 'e', '.'
-> parseNumber();
default -> throw failure(UNEXPECTED_VAL);
};
skipWhitespaces();
return val;
}
/*
* The parsed JsonObject contains a map which holds all lazy member mappings.
* No offsets are required as member values hold their own offsets.
* See https://datatracker.ietf.org/doc/html/rfc8259#section-4
*/
private JsonObject parseObject() {
offset++; // Walk past the '{'
skipWhitespaces();
// Check for empty case
if (charEquals('}')) {
return new JsonObjectImpl(Map.of());
}
var members = new LinkedHashMap<String, JsonValue>();
while (hasInput()) {
// Get the member name, which should be unescaped
// Why not parse the name as a JsonString and then return its value()?
// Would requires 2 passes; we should build the String as we parse.
var name = parseName();
if (members.containsKey(name)) {
throw failure("The duplicate member name: \"%s\" was already parsed".formatted(name));
}
// Move from name to ':'
skipWhitespaces();
if (!charEquals(':')) {
throw failure(
"Expected a colon after the member name");
}
members.put(name, parseValue());
// Ensure current char is either ',' or '}'
if (charEquals('}')) {
return new JsonObjectImpl(members);
} else if (charEquals(',')) {
skipWhitespaces();
} else {
// Neither ',' nor '}' so fail
break;
}
}
throw failure("JSON Object is not closed with a brace");
}
/*
* Member name equality and storage in the map should be done with the
* unescaped value.
* See https://datatracker.ietf.org/doc/html/rfc8259#section-8.3
*/
private String parseName() {
if (!charEquals('"')) {
throw failure("Expecting a JSON Object member name");
}
var escape = false;
boolean useBldr = false;
var start = offset;
for (; hasInput(); offset++) {
var c = doc[offset];
if (escape) {
var escapeLength = 0;
switch (c) {
// Allowed JSON escapes
case '"', '\\', '/' -> {}
case 'b' -> c = '\b';
case 'f' -> c = '\f';
case 'n' -> c = '\n';
case 'r' -> c = '\r';
case 't' -> c = '\t';
case 'u' -> {
c = codeUnit();
escapeLength = 4;
}
default -> throw failure(UNRECOGNIZED_ESCAPE_SEQUENCE.formatted(c));
}
if (!useBldr) {
// Append everything up to the first escape sequence
sb.get().append(doc, start, offset - escapeLength - 1 - start);
useBldr = true;
}
escape = false;
} else if (c == '\\') {
escape = true;
continue;
} else if (c == '\"') {
offset++;
if (useBldr) {
var name = sb.toString();
sb.get().setLength(0);
return name;
} else {
return new String(doc, start, offset - start - 1);
}
} else if (c < ' ') {
throw failure(UNESCAPED_CONTROL_CODE);
}
if (useBldr) {
sb.get().append(c);
}
}
throw failure(UNCLOSED_STRING.formatted("JSON Object member name"));
}
/*
* The parsed JsonArray contains a List which holds all lazy children
* elements. No offsets are required as children values hold their own offsets.
* See https://datatracker.ietf.org/doc/html/rfc8259#section-5
*/
private JsonArray parseArray() {
offset++; // Walk past the '['
skipWhitespaces();
// Check for empty case
if (charEquals(']')) {
return new JsonArrayImpl(List.of());
}
var list = new ArrayList<JsonValue>();
while (hasInput()) {
// Get the JsonValue
list.add(parseValue());
// Ensure current char is either ']' or ','
if (charEquals(']')) {
return new JsonArrayImpl(list);
} else if (!charEquals(',')) {
break;
}
}
throw failure("JSON Array is not closed with a bracket");
}
/*
* The parsed JsonString will contain offsets correlating to the beginning
* and ending quotation marks. All Unicode characters are allowed except the
* following that require escaping: quotation mark, reverse solidus, and the
* control characters (U+0000 through U+001F). Any character may be escaped
* either through a Unicode escape sequence or two-char sequence.
* See https://datatracker.ietf.org/doc/html/rfc8259#section-7
*/
private JsonString parseString() {
int start = offset++; // Move past the starting quote
var escape = false;
boolean hasEscape = false;
for (; hasInput(); offset++) {
var c = doc[offset];
if (escape) {
switch (c) {
// Allowed JSON escapes
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't' -> {}
case 'u' -> codeUnit();
default -> throw failure(UNRECOGNIZED_ESCAPE_SEQUENCE.formatted(c));
}
escape = false;
} else if (c == '\\') {
hasEscape = true;
escape = true;
} else if (c == '\"') {
return new JsonStringImpl(doc, start, ++offset, hasEscape);
} else if (c < ' ') {
throw failure(UNESCAPED_CONTROL_CODE);
}
}
throw failure(UNCLOSED_STRING.formatted("JSON String"));
}
/*
* Parsing true, false, and null return singletons. These JsonValues
* do not require offsets to lazily compute their values.
*/
private JsonBooleanImpl parseTrue() {
offset++;
if (charEquals('r') && charEquals('u') && charEquals('e')) {
return JsonBooleanImpl.TRUE;
}
throw failure(UNEXPECTED_VAL);
}
private JsonBooleanImpl parseFalse() {
offset++;
if (charEquals('a') && charEquals('l') && charEquals('s')
&& charEquals('e')) {
return JsonBooleanImpl.FALSE;
}
throw failure(UNEXPECTED_VAL);
}
private JsonNullImpl parseNull() {
offset++;
if (charEquals('u') && charEquals('l') && charEquals('l')) {
return JsonNullImpl.NULL;
}
throw failure(UNEXPECTED_VAL);
}
/*
* The parsed JsonNumber contains offsets correlating to the first and last
* allowed chars permitted in the JSON numeric grammar:
* number = [ minus ] int [ frac ] [ exp ]
* See https://datatracker.ietf.org/doc/html/rfc8259#section-6
*/
private JsonNumberImpl parseNumber() {
boolean sawDecimal = false;
boolean sawExponent = false;
boolean sawZero = false;
boolean havePart = false;
boolean sawSign = false;
var start = offset;
endloop:
for (; hasInput(); offset++) {
var c = doc[offset];
switch (c) {
case '-' -> {
if (offset != start && !sawExponent || sawSign) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted(c));
}
sawSign = true;
}
case '+' -> {
if (!sawExponent || havePart || sawSign) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted(c));
}
sawSign = true;
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
if (!sawDecimal && !sawExponent && sawZero) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted('0'));
}
if (doc[offset] == '0' && !havePart) {
sawZero = true;
}
havePart = true;
}
case '.' -> {
if (sawDecimal) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted(c));
} else {
if (!havePart) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted(c));
}
sawDecimal = true;
havePart = false;
}
}
case 'e', 'E' -> {
if (sawExponent) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted(c));
} else {
if (!havePart) {
throw failure(INVALID_POSITION_IN_NUMBER.formatted(c));
}
sawExponent = true;
havePart = false;
sawSign = false;
}
}
default -> {
// break the loop for white space or invalid characters
break endloop;
}
}
}
if (!havePart) {
throw failure("Input expected after '[.|e|E]'");
}
return new JsonNumberImpl(doc, start, offset, sawDecimal || sawExponent);
}
// Utility functions
private StringBuilder initSb() {
return new StringBuilder();
}
// Unescapes the Unicode escape sequence and produces a char
private char codeUnit() {
char val = 0;
int end = offset + 4;
if (end >= doc.length) {
throw failure("Invalid Unicode escape sequence. Expected four hex digits");
}
while (offset < end) {
char c = doc[++offset];
val <<= 4;
val += (char) (
switch (c) {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> c - '0';
case 'a', 'b', 'c', 'd', 'e', 'f' -> c - 'a' + 10;
case 'A', 'B', 'C', 'D', 'E', 'F' -> c - 'A' + 10;
default -> throw failure(
"Invalid Unicode escape sequence. '%c' is not a hex digit".formatted(c));
});
}
return val;
}
// Returns true if the parser has not yet reached the end of the Document
private boolean hasInput() {
return offset < doc.length;
}
// Walk to the next non-white space char from the current offset
private void skipWhitespaces() {
while (hasInput()) {
if (notWhitespace()) {
break;
}
offset++;
}
}
// see https://datatracker.ietf.org/doc/html/rfc8259#section-2
private boolean notWhitespace() {
return switch (doc[offset]) {
case ' ', '\t','\r' -> false;
case '\n' -> {
// Increments the row and col
line++;
lineStart = offset + 1;
yield false;
}
default -> true;
};
}
// Returns true if within bounds and if the char at the current parser offset
// is equivalent to the input one. If so, offset is incremented.
private boolean charEquals(char c) {
if (hasInput() && c == doc[offset]) {
offset++;
return true;
}
return false;
}
private JsonParseException failure(String message) {
// Non-revealing message does not produce input source String
return new JsonParseException("%s. Location: row %d, col %d."
.formatted(message, line, offset - lineStart),
line, offset - lineStart);
}
// Parsing error messages ----------------------
private static final String UNEXPECTED_VAL =
"Unexpected value. Expected a JSON Object, Array, String, Number, Boolean, or Null";
private static final String UNRECOGNIZED_ESCAPE_SEQUENCE =
"Unrecognized escape sequence: \"\\%c\"";
private static final String UNESCAPED_CONTROL_CODE =
"Unescaped control code";
private static final String UNCLOSED_STRING =
"%s is not closed with a quotation mark";
private static final String INVALID_POSITION_IN_NUMBER =
"Invalid position of '%c' within JSON Number";
}