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