-
Notifications
You must be signed in to change notification settings - Fork 824
/
JsonParser.java
414 lines (386 loc) · 13.2 KB
/
JsonParser.java
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
/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.json;
import java.util.ArrayList;
import java.util.List;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
/**
* This class converts a stream of JSON tokens into a JSON value.
*
* <p>See ECMA 15.12.
*
* @author Raphael Speyer
* @author Hannes Wallnoefer
*/
public class JsonParser {
private Context cx;
private Scriptable scope;
private int pos;
private int length;
private String src;
public JsonParser(Context cx, Scriptable scope) {
this.cx = cx;
this.scope = scope;
}
public synchronized Object parseValue(String json) throws ParseException {
if (json == null) {
throw new ParseException("Input string may not be null");
}
pos = 0;
length = json.length();
src = json;
Object value = readValue();
consumeWhitespace();
if (pos < length) {
throw new ParseException("Expected end of stream at char " + pos);
}
return value;
}
private Object readValue() throws ParseException {
consumeWhitespace();
while (pos < length) {
char c = src.charAt(pos++);
switch (c) {
case '{':
return readObject();
case '[':
return readArray();
case 't':
return readTrue();
case 'f':
return readFalse();
case '"':
return readString();
case 'n':
return readNull();
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '-':
return readNumber(c);
default:
throw new ParseException("Unexpected token: " + c);
}
}
throw new ParseException("Empty JSON string");
}
private Object readObject() throws ParseException {
consumeWhitespace();
Scriptable object = cx.newObject(scope);
// handle empty object literal case early
if (pos < length && src.charAt(pos) == '}') {
pos += 1;
return object;
}
String id;
Object value;
boolean needsComma = false;
while (pos < length) {
char c = src.charAt(pos++);
switch (c) {
case '}':
if (!needsComma) {
throw new ParseException("Unexpected comma in object literal");
}
return object;
case ',':
if (!needsComma) {
throw new ParseException("Unexpected comma in object literal");
}
needsComma = false;
break;
case '"':
if (needsComma) {
throw new ParseException("Missing comma in object literal");
}
id = readString();
consume(':');
value = readValue();
long index = ScriptRuntime.indexFromString(id);
if (index < 0) {
object.put(id, object, value);
} else {
object.put((int) index, object, value);
}
needsComma = true;
break;
default:
throw new ParseException("Unexpected token in object literal");
}
consumeWhitespace();
}
throw new ParseException("Unterminated object literal");
}
private Object readArray() throws ParseException {
consumeWhitespace();
// handle empty array literal case early
if (pos < length && src.charAt(pos) == ']') {
pos += 1;
return cx.newArray(scope, 0);
}
List<Object> list = new ArrayList<Object>();
boolean needsComma = false;
while (pos < length) {
char c = src.charAt(pos);
switch (c) {
case ']':
if (!needsComma) {
throw new ParseException("Unexpected comma in array literal");
}
pos += 1;
return cx.newArray(scope, list.toArray());
case ',':
if (!needsComma) {
throw new ParseException("Unexpected comma in array literal");
}
needsComma = false;
pos += 1;
break;
default:
if (needsComma) {
throw new ParseException("Missing comma in array literal");
}
list.add(readValue());
needsComma = true;
}
consumeWhitespace();
}
throw new ParseException("Unterminated array literal");
}
private String readString() throws ParseException {
/*
* Optimization: if the source contains no escaped characters, create the
* string directly from the source text.
*/
int stringStart = pos;
while (pos < length) {
char c = src.charAt(pos++);
if (c <= '\u001F') {
throw new ParseException("String contains control character");
} else if (c == '\\') {
break;
} else if (c == '"') {
return src.substring(stringStart, pos - 1);
}
}
/*
* Slow case: string contains escaped characters. Copy a maximal sequence
* of unescaped characters into a temporary buffer, then an escaped
* character, and repeat until the entire string is consumed.
*/
StringBuilder b = new StringBuilder();
while (pos < length) {
assert src.charAt(pos - 1) == '\\';
b.append(src, stringStart, pos - 1);
if (pos >= length) {
throw new ParseException("Unterminated string");
}
char c = src.charAt(pos++);
switch (c) {
case '"':
b.append('"');
break;
case '\\':
b.append('\\');
break;
case '/':
b.append('/');
break;
case 'b':
b.append('\b');
break;
case 'f':
b.append('\f');
break;
case 'n':
b.append('\n');
break;
case 'r':
b.append('\r');
break;
case 't':
b.append('\t');
break;
case 'u':
if (length - pos < 5) {
throw new ParseException(
"Invalid character code: \\u" + src.substring(pos));
}
int code =
fromHex(src.charAt(pos + 0)) << 12
| fromHex(src.charAt(pos + 1)) << 8
| fromHex(src.charAt(pos + 2)) << 4
| fromHex(src.charAt(pos + 3));
if (code < 0) {
throw new ParseException(
"Invalid character code: " + src.substring(pos, pos + 4));
}
pos += 4;
b.append((char) code);
break;
default:
throw new ParseException("Unexpected character in string: '\\" + c + "'");
}
stringStart = pos;
while (pos < length) {
c = src.charAt(pos++);
if (c <= '\u001F') {
throw new ParseException("String contains control character");
} else if (c == '\\') {
break;
} else if (c == '"') {
b.append(src, stringStart, pos - 1);
return b.toString();
}
}
}
throw new ParseException("Unterminated string literal");
}
private static int fromHex(char c) {
return c >= '0' && c <= '9'
? c - '0'
: c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;
}
private Number readNumber(char c) throws ParseException {
assert c == '-' || (c >= '0' && c <= '9');
final int numberStart = pos - 1;
if (c == '-') {
c = nextOrNumberError(numberStart);
if (!(c >= '0' && c <= '9')) {
throw numberError(numberStart, pos);
}
}
if (c != '0') {
readDigits();
}
// read optional fraction part
if (pos < length) {
c = src.charAt(pos);
if (c == '.') {
pos += 1;
c = nextOrNumberError(numberStart);
if (!(c >= '0' && c <= '9')) {
throw numberError(numberStart, pos);
}
readDigits();
}
}
// read optional exponent part
if (pos < length) {
c = src.charAt(pos);
if (c == 'e' || c == 'E') {
pos += 1;
c = nextOrNumberError(numberStart);
if (c == '-' || c == '+') {
c = nextOrNumberError(numberStart);
}
if (!(c >= '0' && c <= '9')) {
throw numberError(numberStart, pos);
}
readDigits();
}
}
String num = src.substring(numberStart, pos);
final double dval = Double.parseDouble(num);
final int ival = (int) dval;
if (ival == dval) {
return Integer.valueOf(ival);
}
return Double.valueOf(dval);
}
private ParseException numberError(int start, int end) {
return new ParseException("Unsupported number format: " + src.substring(start, end));
}
private char nextOrNumberError(int numberStart) throws ParseException {
if (pos >= length) {
throw numberError(numberStart, length);
}
return src.charAt(pos++);
}
private void readDigits() {
for (; pos < length; ++pos) {
char c = src.charAt(pos);
if (!(c >= '0' && c <= '9')) {
break;
}
}
}
private Boolean readTrue() throws ParseException {
if (length - pos < 3
|| src.charAt(pos) != 'r'
|| src.charAt(pos + 1) != 'u'
|| src.charAt(pos + 2) != 'e') {
throw new ParseException("Unexpected token: t");
}
pos += 3;
return Boolean.TRUE;
}
private Boolean readFalse() throws ParseException {
if (length - pos < 4
|| src.charAt(pos) != 'a'
|| src.charAt(pos + 1) != 'l'
|| src.charAt(pos + 2) != 's'
|| src.charAt(pos + 3) != 'e') {
throw new ParseException("Unexpected token: f");
}
pos += 4;
return Boolean.FALSE;
}
private Object readNull() throws ParseException {
if (length - pos < 3
|| src.charAt(pos) != 'u'
|| src.charAt(pos + 1) != 'l'
|| src.charAt(pos + 2) != 'l') {
throw new ParseException("Unexpected token: n");
}
pos += 3;
return null;
}
private void consumeWhitespace() {
while (pos < length) {
char c = src.charAt(pos);
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
pos += 1;
break;
default:
return;
}
}
}
private void consume(char token) throws ParseException {
consumeWhitespace();
if (pos >= length) {
throw new ParseException("Expected " + token + " but reached end of stream");
}
char c = src.charAt(pos++);
if (c == token) {
return;
}
throw new ParseException("Expected " + token + " found " + c);
}
public static class ParseException extends Exception {
private static final long serialVersionUID = 4804542791749920772L;
ParseException(String message) {
super(message);
}
ParseException(Exception cause) {
super(cause);
}
}
}