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 static jdk.nashorn.internal.runtime.Source.sourceFor; 29 30 import java.lang.invoke.MethodHandle; 31 import java.util.Iterator; 32 import java.util.concurrent.Callable; 33 import jdk.nashorn.internal.ir.LiteralNode; 34 import jdk.nashorn.internal.ir.Node; 35 import jdk.nashorn.internal.ir.ObjectNode; 36 import jdk.nashorn.internal.ir.PropertyNode; 37 import jdk.nashorn.internal.ir.UnaryNode; 38 import jdk.nashorn.internal.objects.Global; 39 import jdk.nashorn.internal.parser.JSONParser; 40 import jdk.nashorn.internal.parser.TokenType; 41 import jdk.nashorn.internal.runtime.arrays.ArrayIndex; 42 import jdk.nashorn.internal.runtime.linker.Bootstrap; 43 44 /** 45 * Utilities used by "JSON" object implementation. 46 */ 47 public final class JSONFunctions { 48 private JSONFunctions() {} 49 50 private static final Object REVIVER_INVOKER = new Object(); 51 52 private static MethodHandle getREVIVER_INVOKER() { 53 return Context.getGlobal().getDynamicInvoker(REVIVER_INVOKER, 54 new Callable<MethodHandle>() { 55 @Override 56 public MethodHandle call() { 57 return Bootstrap.createDynamicInvoker("dyn:call", Object.class, 58 ScriptFunction.class, ScriptObject.class, String.class, Object.class); 59 } 60 }); 61 } 62 63 /** 64 * Returns JSON-compatible quoted version of the given string. 65 * 66 * @param str String to be quoted 67 * @return JSON-compatible quoted string 68 */ 69 public static String quote(final String str) { 70 return JSONParser.quote(str); 71 } 72 73 /** 74 * Parses the given JSON text string and returns object representation. 75 * 76 * @param text JSON text to be parsed 77 * @param reviver optional value: function that takes two parameters (key, value) 78 * @return Object representation of JSON text given 79 */ 80 public static Object parse(final Object text, final Object reviver) { 81 final String str = JSType.toString(text); 82 final JSONParser parser = new JSONParser(sourceFor("<json>", str), new Context.ThrowErrorManager()); 83 84 Node node; 85 86 try { 87 node = parser.parse(); 88 } catch (final ParserException e) { 89 throw ECMAErrors.syntaxError(e, "invalid.json", e.getMessage()); 90 } 91 92 final Global global = Context.getGlobal(); 93 final Object unfiltered = convertNode(global, node); 94 return applyReviver(global, unfiltered, reviver); 95 } 96 97 // -- Internals only below this point 98 99 // parse helpers 100 101 // apply 'reviver' function if available 102 private static Object applyReviver(final Global global, final Object unfiltered, final Object reviver) { 103 if (reviver instanceof ScriptFunction) { 104 final ScriptObject root = global.newObject(); 105 root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered); 106 return walk(root, "", (ScriptFunction)reviver); 107 } 108 return unfiltered; 109 } 110 111 // This is the abstract "Walk" operation from the spec. 112 private static Object walk(final ScriptObject holder, final Object name, final ScriptFunction reviver) { 113 final Object val = holder.get(name); 120 final Object newElement = walk(valueObj, key, reviver); 121 122 if (newElement == ScriptRuntime.UNDEFINED) { 123 valueObj.delete(key, false); 124 } else { 125 setPropertyValue(valueObj, key, newElement); 126 } 127 } 128 } 129 130 try { 131 // Object.class, ScriptFunction.class, ScriptObject.class, String.class, Object.class); 132 return getREVIVER_INVOKER().invokeExact(reviver, holder, JSType.toString(name), val); 133 } catch(Error|RuntimeException t) { 134 throw t; 135 } catch(final Throwable t) { 136 throw new RuntimeException(t); 137 } 138 } 139 140 // Converts IR node to runtime value 141 private static Object convertNode(final Global global, final Node node) { 142 if (node instanceof LiteralNode) { 143 // check for array literal 144 if (node.tokenType() == TokenType.ARRAY) { 145 assert node instanceof LiteralNode.ArrayLiteralNode; 146 final Node[] elements = ((LiteralNode.ArrayLiteralNode)node).getValue(); 147 148 // NOTE: We cannot use LiteralNode.isNumericArray() here as that 149 // method uses symbols of element nodes. Since we don't do lower 150 // pass, there won't be any symbols! 151 if (isNumericArray(elements)) { 152 final double[] values = new double[elements.length]; 153 int index = 0; 154 155 for (final Node elem : elements) { 156 values[index++] = JSType.toNumber(convertNode(global, elem)); 157 } 158 return global.wrapAsObject(values); 159 } 160 161 final Object[] values = new Object[elements.length]; 162 int index = 0; 163 164 for (final Node elem : elements) { 165 values[index++] = convertNode(global, elem); 166 } 167 168 return global.wrapAsObject(values); 169 } 170 171 return ((LiteralNode<?>)node).getValue(); 172 173 } else if (node instanceof ObjectNode) { 174 final ObjectNode objNode = (ObjectNode) node; 175 final ScriptObject object = global.newObject(); 176 177 for (final PropertyNode pNode: objNode.getElements()) { 178 final Node valueNode = pNode.getValue(); 179 180 final String name = pNode.getKeyName(); 181 final Object value = convertNode(global, valueNode); 182 setPropertyValue(object, name, value); 183 } 184 185 return object; 186 } else if (node instanceof UnaryNode) { 187 // UnaryNode used only to represent negative number JSON value 188 final UnaryNode unaryNode = (UnaryNode)node; 189 return -((LiteralNode<?>)unaryNode.getExpression()).getNumber(); 190 } else { 191 return null; 192 } 193 } 194 195 // add a new property if does not exist already, or else set old property 196 private static void setPropertyValue(final ScriptObject sobj, final String name, final Object value) { 197 final int index = ArrayIndex.getArrayIndex(name); 198 if (ArrayIndex.isValidArrayIndex(index)) { 199 // array index key 200 sobj.defineOwnProperty(index, value); 201 } else if (sobj.getMap().findProperty(name) != null) { 202 // pre-existing non-inherited property, call set 203 sobj.set(name, value, 0); 204 } else { 205 // add new property 206 sobj.addOwnProperty(name, Property.WRITABLE_ENUMERABLE_CONFIGURABLE, value); 207 } 208 } 209 210 // does the given IR node represent a numeric array? 211 private static boolean isNumericArray(final Node[] values) { 212 for (final Node node : values) { 213 if (node instanceof LiteralNode && ((LiteralNode<?>)node).getValue() instanceof Number) { 214 continue; 215 } 216 return false; 217 } 218 return true; 219 } 220 } | 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); 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 } |