Debian Codegraph @

rhino/src/org/mozilla/javascript/json/JsonParser.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.json;
8
9 import org.mozilla.javascript.Context;
10 import org.mozilla.javascript.Scriptable;
11 import org.mozilla.javascript.ScriptRuntime;
12
13 import java.util.ArrayList;
14 import java.util.List;
15
16 /**
17 * This class converts a stream of JSON tokens into a JSON value.
18 *
19 * See ECMA 15.12.
20 * @author Raphael Speyer
21 * @author Hannes Wallnoefer
22 */
23 public class JsonParser {
24
25 private Context cx;
26 private Scriptable scope;
27
28 private int pos;
29 private int length;
30 private String src;
31
32 public JsonParser(Context cx, Scriptable scope) {
33 this.cx = cx;
34 this.scope = scope;
35 }
36
37 public synchronized Object parseValue(String json) throws ParseException {
38 if (json == null) {
39 throw new ParseException("Input string may not be null");
40 }
41 pos = 0;
42 length = json.length();
43 src = json;
44 Object value = readValue();
45 consumeWhitespace();
46 if (pos < length) {
47 throw new ParseException("Expected end of stream at char " + pos);
48 }
49 return value;
50 }
51
52 private Object readValue() throws ParseException {
53 consumeWhitespace();
54 while (pos < length) {
55 char c = src.charAt(pos++);
56 switch (c) {
57 case '{':
58 return readObject();
59 case '[':
60 return readArray();
61 case 't':
62 return readTrue();
63 case 'f':
64 return readFalse();
65 case '"':
66 return readString();
67 case 'n':
68 return readNull();
69 case '1':
70 case '2':
71 case '3':
72 case '4':
73 case '5':
74 case '6':
75 case '7':
76 case '8':
77 case '9':
78 case '0':
79 case '-':
80 return readNumber(c);
81 default:
82 throw new ParseException("Unexpected token: " + c);
83 }
84 }
85 throw new ParseException("Empty JSON string");
86 }
87
88 private Object readObject() throws ParseException {
89 consumeWhitespace();
90 Scriptable object = cx.newObject(scope);
91 // handle empty object literal case early
92 if (pos < length && src.charAt(pos) == '}') {
93 pos += 1;
94 return object;
95 }
96 String id;
97 Object value;
98 boolean needsComma = false;
99 while (pos < length) {
100 char c = src.charAt(pos++);
101 switch(c) {
102 case '}':
103 if (!needsComma) {
104 throw new ParseException("Unexpected comma in object literal");
105 }
106 return object;
107 case ',':
108 if (!needsComma) {
109 throw new ParseException("Unexpected comma in object literal");
110 }
111 needsComma = false;
112 break;
113 case '"':
114 if (needsComma) {
115 throw new ParseException("Missing comma in object literal");
116 }
117 id = readString();
118 consume(':');
119 value = readValue();
120
121 long index = ScriptRuntime.indexFromString(id);
122 if (index < 0) {
123 object.put(id, object, value);
124 } else {
125 object.put((int)index, object, value);
126 }
127
128 needsComma = true;
129 break;
130 default:
131 throw new ParseException("Unexpected token in object literal");
132 }
133 consumeWhitespace();
134 }
135 throw new ParseException("Unterminated object literal");
136 }
137
138 private Object readArray() throws ParseException {
139 consumeWhitespace();
140 // handle empty array literal case early
141 if (pos < length && src.charAt(pos) == ']') {
142 pos += 1;
143 return cx.newArray(scope, 0);
144 }
145 List<Object> list = new ArrayList<Object>();
146 boolean needsComma = false;
147 while (pos < length) {
148 char c = src.charAt(pos);
149 switch(c) {
150 case ']':
151 if (!needsComma) {
152 throw new ParseException("Unexpected comma in array literal");
153 }
154 pos += 1;
155 return cx.newArray(scope, list.toArray());
156 case ',':
157 if (!needsComma) {
158 throw new ParseException("Unexpected comma in array literal");
159 }
160 needsComma = false;
161 pos += 1;
162 break;
163 default:
164 if (needsComma) {
165 throw new ParseException("Missing comma in array literal");
166 }
167 list.add(readValue());
168 needsComma = true;
169 }
170 consumeWhitespace();
171 }
172 throw new ParseException("Unterminated array literal");
173 }
174
175 private String readString() throws ParseException {
176 /*
177 * Optimization: if the source contains no escaped characters, create the
178 * string directly from the source text.
179 */
180 int stringStart = pos;
181 while (pos < length) {
182 char c = src.charAt(pos++);
183 if (c <= '\u001F') {
184 throw new ParseException("String contains control character");
185 } else if (c == '\\') {
186 break;
187 } else if (c == '"') {
188 return src.substring(stringStart, pos - 1);
189 }
190 }
191
192 /*
193 * Slow case: string contains escaped characters. Copy a maximal sequence
194 * of unescaped characters into a temporary buffer, then an escaped
195 * character, and repeat until the entire string is consumed.
196 */
197 StringBuilder b = new StringBuilder();
198 while (pos < length) {
199 assert src.charAt(pos - 1) == '\\';
200 b.append(src, stringStart, pos - 1);
201 if (pos >= length) {
202 throw new ParseException("Unterminated string");
203 }
204 char c = src.charAt(pos++);
205 switch (c) {
206 case '"':
207 b.append('"');
208 break;
209 case '\\':
210 b.append('\\');
211 break;
212 case '/':
213 b.append('/');
214 break;
215 case 'b':
216 b.append('\b');
217 break;
218 case 'f':
219 b.append('\f');
220 break;
221 case 'n':
222 b.append('\n');
223 break;
224 case 'r':
225 b.append('\r');
226 break;
227 case 't':
228 b.append('\t');
229 break;
230 case 'u':
231 if (length - pos < 5) {
232 throw new ParseException("Invalid character code: \\u" + src.substring(pos));
233 }
234 int code = fromHex(src.charAt(pos + 0)) << 12
235 | fromHex(src.charAt(pos + 1)) << 8
236 | fromHex(src.charAt(pos + 2)) << 4
237 | fromHex(src.charAt(pos + 3));
238 if (code < 0) {
239 throw new ParseException("Invalid character code: " + src.substring(pos, pos + 4));
240 }
241 pos += 4;
242 b.append((char) code);
243 break;
244 default:
245 throw new ParseException("Unexpected character in string: '\\" + c + "'");
246 }
247 stringStart = pos;
248 while (pos < length) {
249 c = src.charAt(pos++);
250 if (c <= '\u001F') {
251 throw new ParseException("String contains control character");
252 } else if (c == '\\') {
253 break;
254 } else if (c == '"') {
255 b.append(src, stringStart, pos - 1);
256 return b.toString();
257 }
258 }
259 }
260 throw new ParseException("Unterminated string literal");
261 }
262
263 private int fromHex(char c) {
264 return c >= '0' && c <= '9' ? c - '0'
265 : c >= 'A' && c <= 'F' ? c - 'A' + 10
266 : c >= 'a' && c <= 'f' ? c - 'a' + 10
267 : -1;
268 }
269
270 private Number readNumber(char c) throws ParseException {
271 assert c == '-' || (c >= '0' && c <= '9');
272 final int numberStart = pos - 1;
273 if (c == '-') {
274 c = nextOrNumberError(numberStart);
275 if (!(c >= '0' && c <= '9')) {
276 throw numberError(numberStart, pos);
277 }
278 }
279 if (c != '0') {
280 readDigits();
281 }
282 // read optional fraction part
283 if (pos < length) {
284 c = src.charAt(pos);
285 if (c == '.') {
286 pos += 1;
287 c = nextOrNumberError(numberStart);
288 if (!(c >= '0' && c <= '9')) {
289 throw numberError(numberStart, pos);
290 }
291 readDigits();
292 }
293 }
294 // read optional exponent part
295 if (pos < length) {
296 c = src.charAt(pos);
297 if (c == 'e' || c == 'E') {
298 pos += 1;
299 c = nextOrNumberError(numberStart);
300 if (c == '-' || c == '+') {
301 c = nextOrNumberError(numberStart);
302 }
303 if (!(c >= '0' && c <= '9')) {
304 throw numberError(numberStart, pos);
305 }
306 readDigits();
307 }
308 }
309 String num = src.substring(numberStart, pos);
310 final double dval = Double.parseDouble(num);
311 final int ival = (int)dval;
312 if (ival == dval) {
313 return Integer.valueOf(ival);
314 } else {
315 return Double.valueOf(dval);
316 }
317 }
318
319 private ParseException numberError(int start, int end) {
320 return new ParseException("Unsupported number format: " + src.substring(start, end));
321 }
322
323 private char nextOrNumberError(int numberStart) throws ParseException {
324 if (pos >= length) {
325 throw numberError(numberStart, length);
326 }
327 return src.charAt(pos++);
328 }
329
330 private void readDigits() {
331 for (; pos < length; ++pos) {
332 char c = src.charAt(pos);
333 if (!(c >= '0' && c <= '9')) {
334 break;
335 }
336 }
337 }
338
339 private Boolean readTrue() throws ParseException {
340 if (length - pos < 3
341 || src.charAt(pos) != 'r'
342 || src.charAt(pos + 1) != 'u'
343 || src.charAt(pos + 2) != 'e') {
344 throw new ParseException("Unexpected token: t");
345 }
346 pos += 3;
347 return Boolean.TRUE;
348 }
349
350 private Boolean readFalse() throws ParseException {
351 if (length - pos < 4
352 || src.charAt(pos) != 'a'
353 || src.charAt(pos + 1) != 'l'
354 || src.charAt(pos + 2) != 's'
355 || src.charAt(pos + 3) != 'e') {
356 throw new ParseException("Unexpected token: f");
357 }
358 pos += 4;
359 return Boolean.FALSE;
360 }
361
362 private Object readNull() throws ParseException {
363 if (length - pos < 3
364 || src.charAt(pos) != 'u'
365 || src.charAt(pos + 1) != 'l'
366 || src.charAt(pos + 2) != 'l') {
367 throw new ParseException("Unexpected token: n");
368 }
369 pos += 3;
370 return null;
371 }
372
373 private void consumeWhitespace() {
374 while (pos < length) {
375 char c = src.charAt(pos);
376 switch (c) {
377 case ' ':
378 case '\t':
379 case '\r':
380 case '\n':
381 pos += 1;
382 break;
383 default:
384 return;
385 }
386 }
387 }
388
389 private void consume(char token) throws ParseException {
390 consumeWhitespace();
391 if (pos >= length) {
392 throw new ParseException("Expected " + token + " but reached end of stream");
393 }
394 char c = src.charAt(pos++);
395 if (c == token) {
396 return;
397 } else {
398 throw new ParseException("Expected " + token + " found " + c);
399 }
400 }
401
402 public static class ParseException extends Exception {
403
404 static final long serialVersionUID = 4804542791749920772L;
405
406 ParseException(String message) {
407 super(message);
408 }
409
410 ParseException(Exception cause) {
411 super(cause);
412 }
413 }
414
415 }