Debian Codegraph @

rhino/src/org/mozilla/javascript/NativeJSON.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;
8
9 import org.mozilla.javascript.json.JsonParser;
10
11 import java.util.Stack;
12 import java.util.Collection;
13 import java.util.Iterator;
14 import java.util.Arrays;
15 import java.util.List;
16 import java.util.LinkedList;
17
18 /**
19 * This class implements the JSON native object.
20 * See ECMA 15.12.
21 * @author Matthew Crumley, Raphael Speyer
22 */
23 public final class NativeJSON extends IdScriptableObject
24 {
25 static final long serialVersionUID = -4567599697595654984L;
26
27 private static final Object JSON_TAG = "JSON";
28
29 private static final int MAX_STRINGIFY_GAP_LENGTH = 10;
30
31 static void init(Scriptable scope, boolean sealed)
32 {
33 NativeJSON obj = new NativeJSON();
34 obj.activatePrototypeMap(MAX_ID);
35 obj.setPrototype(getObjectPrototype(scope));
36 obj.setParentScope(scope);
37 if (sealed) { obj.sealObject(); }
38 ScriptableObject.defineProperty(scope, "JSON", obj,
39 ScriptableObject.DONTENUM);
40 }
41
42 private NativeJSON()
43 {
44 }
45
46 @Override
47 public String getClassName() { return "JSON"; }
48
49 @Override
50 protected void initPrototypeId(int id)
51 {
52 if (id <= LAST_METHOD_ID) {
53 String name;
54 int arity;
55 switch (id) {
56 case Id_toSource: arity = 0; name = "toSource"; break;
57 case Id_parse: arity = 2; name = "parse"; break;
58 case Id_stringify: arity = 3; name = "stringify"; break;
59 default: throw new IllegalStateException(String.valueOf(id));
60 }
61 initPrototypeMethod(JSON_TAG, id, name, arity);
62 } else {
63 throw new IllegalStateException(String.valueOf(id));
64 }
65 }
66
67 @Override
68 public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
69 Scriptable thisObj, Object[] args)
70 {
71 if (!f.hasTag(JSON_TAG)) {
72 return super.execIdCall(f, cx, scope, thisObj, args);
73 }
74 int methodId = f.methodId();
75 switch (methodId) {
76 case Id_toSource:
77 return "JSON";
78
79 case Id_parse: {
80 String jtext = ScriptRuntime.toString(args, 0);
81 Object reviver = null;
82 if (args.length > 1) {
83 reviver = args[1];
84 }
85 if (reviver instanceof Callable) {
86 return parse(cx, scope, jtext, (Callable) reviver);
87 } else {
88 return parse(cx, scope, jtext);
89 }
90 }
91
92 case Id_stringify: {
93 Object value = null, replacer = null, space = null;
94 switch (args.length) {
95 case 3: space = args[2];
96 /* fallthru */ case 2: replacer = args[1];
97 /* fallthru */ case 1: value = args[0];
98 /* fallthru */ case 0:
99 /* fallthru */ default:
100 }
101 return stringify(cx, scope, value, replacer, space);
102 }
103
104 default: throw new IllegalStateException(String.valueOf(methodId));
105 }
106 }
107
108 private static Object parse(Context cx, Scriptable scope, String jtext) {
109 try {
110 return new JsonParser(cx, scope).parseValue(jtext);
111 } catch (JsonParser.ParseException ex) {
112 throw ScriptRuntime.constructError("SyntaxError", ex.getMessage());
113 }
114 }
115
116 public static Object parse(Context cx, Scriptable scope, String jtext,
117 Callable reviver)
118 {
119 Object unfiltered = parse(cx, scope, jtext);
120 Scriptable root = cx.newObject(scope);
121 root.put("", root, unfiltered);
122 return walk(cx, scope, reviver, root, "");
123 }
124
125 private static Object walk(Context cx, Scriptable scope, Callable reviver,
126 Scriptable holder, Object name)
127 {
128 final Object property;
129 if (name instanceof Number) {
130 property = holder.get( ((Number) name).intValue(), holder);
131 } else {
132 property = holder.get( ((String) name), holder);
133 }
134
135 if (property instanceof Scriptable) {
136 Scriptable val = ((Scriptable) property);
137 if (val instanceof NativeArray) {
138 long len = ((NativeArray) val).getLength();
139 for (long i = 0; i < len; i++) {
140 // indices greater than MAX_INT are represented as strings
141 if (i > Integer.MAX_VALUE) {
142 String id = Long.toString(i);
143 Object newElement = walk(cx, scope, reviver, val, id);
144 if (newElement == Undefined.instance) {
145 val.delete(id);
146 } else {
147 val.put(id, val, newElement);
148 }
149 } else {
150 int idx = (int) i;
151 Object newElement = walk(cx, scope, reviver, val, idx);
152 if (newElement == Undefined.instance) {
153 val.delete(idx);
154 } else {
155 val.put(idx, val, newElement);
156 }
157 }
158 }
159 } else {
160 Object[] keys = val.getIds();
161 for (Object p : keys) {
162 Object newElement = walk(cx, scope, reviver, val, p);
163 if (newElement == Undefined.instance) {
164 if (p instanceof Number)
165 val.delete(((Number) p).intValue());
166 else
167 val.delete((String) p);
168 } else {
169 if (p instanceof Number)
170 val.put(((Number) p).intValue(), val, newElement);
171 else
172 val.put((String) p, val, newElement);
173 }
174 }
175 }
176 }
177
178 return reviver.call(cx, scope, holder, new Object[] { name, property });
179 }
180
181 private static String repeat(char c, int count) {
182 char chars[] = new char[count];
183 Arrays.fill(chars, c);
184 return new String(chars);
185 }
186
187 private static class StringifyState {
188 StringifyState(Context cx, Scriptable scope, String indent, String gap,
189 Callable replacer, List<Object> propertyList,
190 Object space)
191 {
192 this.cx = cx;
193 this.scope = scope;
194
195 this.indent = indent;
196 this.gap = gap;
197 this.replacer = replacer;
198 this.propertyList = propertyList;
199 this.space = space;
200 }
201
202 Stack<Scriptable> stack = new Stack<Scriptable>();
203 String indent;
204 String gap;
205 Callable replacer;
206 List<Object> propertyList;
207 Object space;
208
209 Context cx;
210 Scriptable scope;
211 }
212
213 public static Object stringify(Context cx, Scriptable scope, Object value,
214 Object replacer, Object space)
215 {
216 String indent = "";
217 String gap = "";
218
219 List<Object> propertyList = null;
220 Callable replacerFunction = null;
221
222 if (replacer instanceof Callable) {
223 replacerFunction = (Callable) replacer;
224 } else if (replacer instanceof NativeArray) {
225 propertyList = new LinkedList<Object>();
226 NativeArray replacerArray = (NativeArray) replacer;
227 for (int i : replacerArray.getIndexIds()) {
228 Object v = replacerArray.get(i, replacerArray);
229 if (v instanceof String || v instanceof Number) {
230 propertyList.add(v);
231 } else if (v instanceof NativeString || v instanceof NativeNumber) {
232 propertyList.add(ScriptRuntime.toString(v));
233 }
234 }
235 }
236
237 if (space instanceof NativeNumber) {
238 space = ScriptRuntime.toNumber(space);
239 } else if (space instanceof NativeString) {
240 space = ScriptRuntime.toString(space);
241 }
242
243 if (space instanceof Number) {
244 int gapLength = (int) ScriptRuntime.toInteger(space);
245 gapLength = Math.min(MAX_STRINGIFY_GAP_LENGTH, gapLength);
246 gap = (gapLength > 0) ? repeat(' ', gapLength) : "";
247 space = gapLength;
248 } else if (space instanceof String) {
249 gap = (String) space;
250 if (gap.length() > MAX_STRINGIFY_GAP_LENGTH) {
251 gap = gap.substring(0, MAX_STRINGIFY_GAP_LENGTH);
252 }
253 }
254
255 StringifyState state = new StringifyState(cx, scope,
256 indent,
257 gap,
258 replacerFunction,
259 propertyList,
260 space);
261
262 ScriptableObject wrapper = new NativeObject();
263 wrapper.setParentScope(scope);
264 wrapper.setPrototype(ScriptableObject.getObjectPrototype(scope));
265 wrapper.defineProperty("", value, 0);
266 return str("", wrapper, state);
267 }
268
269 private static Object str(Object key, Scriptable holder,
270 StringifyState state)
271 {
272 Object value = null;
273 if (key instanceof String) {
274 value = getProperty(holder, (String) key);
275 } else {
276 value = getProperty(holder, ((Number) key).intValue());
277 }
278
279 if (value instanceof Scriptable && hasProperty((Scriptable) value, "toJSON")) {
280 Object toJSON = getProperty((Scriptable) value, "toJSON");
281 if (toJSON instanceof Callable) {
282 value = callMethod(state.cx, (Scriptable) value, "toJSON",
283 new Object[] { key });
284 }
285 }
286
287 if (state.replacer != null) {
288 value = state.replacer.call(state.cx, state.scope, holder,
289 new Object[] { key, value });
290 }
291
292
293 if (value instanceof NativeNumber) {
294 value = ScriptRuntime.toNumber(value);
295 } else if (value instanceof NativeString) {
296 value = ScriptRuntime.toString(value);
297 } else if (value instanceof NativeBoolean) {
298 value = ((NativeBoolean) value).getDefaultValue(ScriptRuntime.BooleanClass);
299 }
300
301 if (value == null) return "null";
302 if (value.equals(Boolean.TRUE)) return "true";
303 if (value.equals(Boolean.FALSE)) return "false";
304
305 if (value instanceof CharSequence) {
306 return quote(value.toString());
307 }
308
309 if (value instanceof Number) {
310 double d = ((Number) value).doubleValue();
311 if (d == d && d != Double.POSITIVE_INFINITY &&
312 d != Double.NEGATIVE_INFINITY)
313 {
314 return ScriptRuntime.toString(value);
315 } else {
316 return "null";
317 }
318 }
319
320 if (value instanceof Scriptable && !(value instanceof Callable)) {
321 if (value instanceof NativeArray) {
322 return ja((NativeArray) value, state);
323 }
324 return jo((Scriptable) value, state);
325 }
326
327 return Undefined.instance;
328 }
329
330 private static String join(Collection<Object> objs, String delimiter) {
331 if (objs == null || objs.isEmpty()) {
332 return "";
333 }
334 Iterator<Object> iter = objs.iterator();
335 if (!iter.hasNext()) return "";
336 StringBuilder builder = new StringBuilder(iter.next().toString());
337 while (iter.hasNext()) {
338 builder.append(delimiter).append(iter.next().toString());
339 }
340 return builder.toString();
341 }
342
343 private static String jo(Scriptable value, StringifyState state) {
344 if (state.stack.search(value) != -1) {
345 throw ScriptRuntime.typeError0("msg.cyclic.value");
346 }
347 state.stack.push(value);
348
349 String stepback = state.indent;
350 state.indent = state.indent + state.gap;
351 Object[] k = null;
352 if (state.propertyList != null) {
353 k = state.propertyList.toArray();
354 } else {
355 k = value.getIds();
356 }
357
358 List<Object> partial = new LinkedList<Object>();
359
360 for (Object p : k) {
361 Object strP = str(p, value, state);
362 if (strP != Undefined.instance) {
363 String member = quote(p.toString()) + ":";
364 if (state.gap.length() > 0) {
365 member = member + " ";
366 }
367 member = member + strP;
368 partial.add(member);
369 }
370 }
371
372 final String finalValue;
373
374 if (partial.isEmpty()) {
375 finalValue = "{}";
376 } else {
377 if (state.gap.length() == 0) {
378 finalValue = '{' + join(partial, ",") + '}';
379 } else {
380 String separator = ",\n" + state.indent;
381 String properties = join(partial, separator);
382 finalValue = "{\n" + state.indent + properties + '\n' +
383 stepback + '}';
384 }
385 }
386
387 state.stack.pop();
388 state.indent = stepback;
389 return finalValue;
390 }
391
392 private static String ja(NativeArray value, StringifyState state) {
393 if (state.stack.search(value) != -1) {
394 throw ScriptRuntime.typeError0("msg.cyclic.value");
395 }
396 state.stack.push(value);
397
398 String stepback = state.indent;
399 state.indent = state.indent + state.gap;
400 List<Object> partial = new LinkedList<Object>();
401
402 long len = value.getLength();
403 for (long index = 0; index < len; index++) {
404 Object strP;
405 if (index > Integer.MAX_VALUE) {
406 strP = str(Long.toString(index), value, state);
407 } else {
408 strP = str((int) index, value, state);
409 }
410 if (strP == Undefined.instance) {
411 partial.add("null");
412 } else {
413 partial.add(strP);
414 }
415 }
416
417 final String finalValue;
418
419 if (partial.isEmpty()) {
420 finalValue = "[]";
421 } else {
422 if (state.gap.length() == 0) {
423 finalValue = '[' + join(partial, ",") + ']';
424 } else {
425 String separator = ",\n" + state.indent;
426 String properties = join(partial, separator);
427 finalValue = "[\n" + state.indent + properties + '\n' + stepback + ']';
428 }
429 }
430
431 state.stack.pop();
432 state.indent = stepback;
433 return finalValue;
434 }
435
436 private static String quote(String string) {
437 StringBuilder product = new StringBuilder(string.length()+2); // two extra chars for " on either side
438 product.append('"');
439 int length = string.length();
440 for (int i = 0; i < length; i++) {
441 char c = string.charAt(i);
442 switch (c) {
443 case '"':
444 product.append("\\\"");
445 break;
446 case '\\':
447 product.append("\\\\");
448 break;
449 case '\b':
450 product.append("\\b");
451 break;
452 case '\f':
453 product.append("\\f");
454 break;
455 case '\n':
456 product.append("\\n");
457 break;
458 case '\r':
459 product.append("\\r");
460 break;
461 case '\t':
462 product.append("\\t");
463 break;
464 default:
465 if (c < ' ') {
466 product.append("\\u");
467 String hex = String.format("%04x", (int) c);
468 product.append(hex);
469 }
470 else {
471 product.append(c);
472 }
473 break;
474 }
475 }
476 product.append('"');
477 return product.toString();
478 }
479
480 // #string_id_map#
481
482 @Override
483 protected int findPrototypeId(String s)
484 {
485 int id;
486 // #generated# Last update: 2009-05-25 16:01:00 EDT
487 { id = 0; String X = null;
488 L: switch (s.length()) {
489 case 5: X="parse";id=Id_parse; break L;
490 case 8: X="toSource";id=Id_toSource; break L;
491 case 9: X="stringify";id=Id_stringify; break L;
492 }
493 if (X!=null && X!=s && !X.equals(s)) id = 0;
494 }
495 // #/generated#
496 return id;
497 }
498
499 private static final int
500 Id_toSource = 1,
501 Id_parse = 2,
502 Id_stringify = 3,
503 LAST_METHOD_ID = 3,
504 MAX_ID = 3;
505
506 // #/string_id_map#
507 }