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