1 /* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package jdk.nashorn.internal.runtime; 27 28 import java.lang.invoke.MethodHandle; 29 import java.util.ArrayList; 30 import java.util.Iterator; 31 import java.util.List; 32 import java.util.Map; 33 import java.util.concurrent.Callable; 34 import jdk.nashorn.internal.codegen.ObjectClassGenerator; 35 import jdk.nashorn.internal.objects.Global; 36 import jdk.nashorn.internal.parser.JSONParser; 37 import jdk.nashorn.internal.runtime.arrays.ArrayData; 38 import jdk.nashorn.internal.runtime.arrays.ArrayIndex; 39 import jdk.nashorn.internal.runtime.linker.Bootstrap; 40 import jdk.nashorn.internal.scripts.JO; 41 42 /** 43 * Utilities used by "JSON" object implementation. 44 */ 45 public final class JSONFunctions { 46 private JSONFunctions() {} 47 48 private static final Object REVIVER_INVOKER = new Object(); 49 50 private static MethodHandle getREVIVER_INVOKER() { 51 return Context.getGlobal().getDynamicInvoker(REVIVER_INVOKER, 52 new Callable<MethodHandle>() { 53 @Override 54 public MethodHandle call() { 55 return Bootstrap.createDynamicInvoker("dyn:call", Object.class, 56 ScriptFunction.class, ScriptObject.class, String.class, Object.class); 57 } 58 }); 59 } 60 61 /** 62 * Returns JSON-compatible quoted version of the given string. 63 * 64 * @param str String to be quoted 65 * @return JSON-compatible quoted string 66 */ 67 public static String quote(final String str) { 68 return JSONParser.quote(str); 69 } 70 71 /** 72 * Parses the given JSON text string and returns object representation. 73 * 74 * @param text JSON text to be parsed 75 * @param reviver optional value: function that takes two parameters (key, value) 76 * @return Object representation of JSON text given 77 */ 78 public static Object parse(final Object text, final Object reviver) { 79 final String str = JSType.toString(text); 80 final Global global = Context.getGlobal(); 81 final JSONParser parser = new JSONParser(str); 82 final Object value; 83 84 try { 85 value = parser.parse(); 86 } catch (final ParserException e) { 87 throw ECMAErrors.syntaxError(e, "invalid.json", e.getMessage()); 88 } 89 90 final Object unfiltered = convert(global, Global.objectPrototype(), value); 91 return applyReviver(global, unfiltered, reviver); 92 } 93 94 // -- Internals only below this point 95 96 // parse helpers 97 98 // apply 'reviver' function if available 99 private static Object applyReviver(final Global global, final Object unfiltered, final Object reviver) { 100 if (reviver instanceof ScriptFunction) { 101 final ScriptObject root = global.newObject(); 102 root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered); 103 return walk(root, "", (ScriptFunction)reviver); 104 } 105 return unfiltered; 106 } 107 108 // This is the abstract "Walk" operation from the spec. 109 private static Object walk(final ScriptObject holder, final Object name, final ScriptFunction reviver) { 110 final Object val = holder.get(name); 111 if (val instanceof ScriptObject) { 112 final ScriptObject valueObj = (ScriptObject)val; 113 final Iterator<String> iter = valueObj.propertyIterator(); 114 115 while (iter.hasNext()) { 116 final String key = iter.next(); 117 final Object newElement = walk(valueObj, key, reviver); 118 119 if (newElement == ScriptRuntime.UNDEFINED) { 120 valueObj.delete(key, false); 121 } else { 122 setPropertyValue(valueObj, key, newElement); 123 } 124 } 125 } 126 127 try { 128 // Object.class, ScriptFunction.class, ScriptObject.class, String.class, Object.class); 129 return getREVIVER_INVOKER().invokeExact(reviver, holder, JSType.toString(name), val); 130 } catch(Error|RuntimeException t) { 131 throw t; 132 } catch(final Throwable t) { 133 throw new RuntimeException(t); 134 } 135 } 136 137 // Converts collections to JS objects 138 @SuppressWarnings("unchecked") 139 private static Object convert(final Global global, final ScriptObject objectProto, final Object value) { 140 if (value instanceof Map) { 141 142 final Map<String, Object> map = (Map) value; 143 final int length = map.size(); 144 final List<Property> properties = new ArrayList<>(length); 145 final Object[] objectSpill = new Object[length]; 146 final long[] primitiveSpill = new long[length]; 147 ArrayData arrayData = ArrayData.EMPTY_ARRAY; 148 int slot = 0; 149 150 for (final Map.Entry<String, Object> entry : map.entrySet()) { 151 final String name = entry.getKey(); 152 final Object convertedValue = convert(global, objectProto, entry.getValue()); 153 final int index = ArrayIndex.getArrayIndex(name); 154 if (ArrayIndex.isValidArrayIndex(index)) { 155 // array index key 156 final long oldLength = arrayData.length(); 157 final long longIndex = ArrayIndex.toLongIndex(index); 158 if (longIndex > oldLength) { 159 if (arrayData.canDelete(oldLength, longIndex - 1, false)) { 160 arrayData = arrayData.delete(oldLength, longIndex - 1); 161 } 162 } 163 arrayData = arrayData.ensure(longIndex).set(index, convertedValue, false); 164 } else { 165 // ordinary property key 166 final Class<?> type; 167 if (ObjectClassGenerator.OBJECT_FIELDS_ONLY) { 168 objectSpill[slot] = convertedValue; 169 type = Object.class; 170 } else { 171 type = getType(convertedValue); 172 if (type == Object.class) { 173 objectSpill[slot] = convertedValue; 174 } else { 175 primitiveSpill[slot] = ObjectClassGenerator.pack((Number) convertedValue); 176 } 177 } 178 final Property property = new SpillProperty(name, 0, slot++); 179 property.setType(type); 180 properties.add(property); 181 } 182 } 183 184 final ScriptObject result = new JO(PropertyMap.newMap(properties), primitiveSpill, objectSpill); 185 result.setInitialProto(objectProto); 186 result.setArray(arrayData); 187 return result; 188 189 } else if (value instanceof List) { 190 191 final List<Object> list = (List) value; 192 if (isNumericArray(list)) { 193 final double[] values = new double[list.size()]; 194 int index = 0; 195 196 for (final Object obj : list) { 197 values[index++] = JSType.toNumber(obj); 198 } 199 return global.wrapAsObject(values); 200 } 201 202 final Object[] values = new Object[list.size()]; 203 int index = 0; 204 205 for (final Object elem : list) { 206 values[index++] = convert(global, objectProto, elem); 207 } 208 209 return global.wrapAsObject(values); 210 } 211 212 return value; 213 } 214 215 216 private static Class<?> getType(final Object value) { 217 if (value instanceof Integer) { 218 return int.class; 219 } else if (value instanceof Long) { 220 return long.class; 221 } else if (value instanceof Double) { 222 return double.class; 223 } else { 224 return Object.class; 225 } 226 } 227 228 // add a new property if does not exist already, or else set old property 229 private static void setPropertyValue(final ScriptObject sobj, final String name, final Object value) { 230 final int index = ArrayIndex.getArrayIndex(name); 231 if (ArrayIndex.isValidArrayIndex(index)) { 232 // array index key 233 sobj.defineOwnProperty(index, value); 234 } else if (sobj.getMap().findProperty(name) != null) { 235 // pre-existing non-inherited property, call set 236 sobj.set(name, value, 0); 237 } else { 238 // add new property 239 sobj.addOwnProperty(name, Property.WRITABLE_ENUMERABLE_CONFIGURABLE, value); 240 } 241 } 242 243 // does the given list represent a numeric array? 244 private static boolean isNumericArray(final List<Object> list) { 245 for (final Object obj : list) { 246 if (!(obj instanceof Number)) { 247 return false; 248 } 249 } 250 return true; 251 } 252 }