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.Iterator;
  30 import java.util.List;
  31 import jdk.nashorn.internal.ir.LiteralNode;
  32 import jdk.nashorn.internal.ir.Node;
  33 import jdk.nashorn.internal.ir.ObjectNode;
  34 import jdk.nashorn.internal.ir.PropertyNode;
  35 import jdk.nashorn.internal.ir.UnaryNode;
  36 import jdk.nashorn.internal.parser.JSONParser;
  37 import jdk.nashorn.internal.parser.TokenType;
  38 import jdk.nashorn.internal.runtime.linker.Bootstrap;
  39 import static jdk.nashorn.internal.runtime.arrays.ArrayIndex.getArrayIndexNoThrow;
  40 import static jdk.nashorn.internal.runtime.arrays.ArrayIndex.isValidArrayIndex;
  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                 (context != null) ?
  74                     context.getEnv()._strict :
  75                     false);
  76 
  77         Node node;
  78 
  79         try {
  80             node = parser.parse();
  81         } catch (final ParserException e) {
  82             throw ECMAErrors.syntaxError(e, "invalid.json", e.getMessage());
  83         }
  84 
  85         final ScriptObject global = Context.getGlobalTrusted();
  86         Object unfiltered = convertNode(global, node);
  87         return applyReviver(global, unfiltered, reviver);
  88     }
  89 
  90     // -- Internals only below this point
  91 
  92     // parse helpers
  93 
  94     // apply 'reviver' function if available
  95     private static Object applyReviver(final ScriptObject global, final Object unfiltered, final Object reviver) {
  96         if (reviver instanceof ScriptFunction) {
  97             assert global instanceof GlobalObject;
  98             final ScriptObject root = ((GlobalObject)global).newObject();
  99             root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered);
 100             return walk(root, "", (ScriptFunction)reviver);
 101         }
 102         return unfiltered;
 103     }
 104 
 105     // This is the abstract "Walk" operation from the spec.
 106     private static Object walk(final ScriptObject holder, final Object name, final ScriptFunction reviver) {
 107         final Object val = holder.get(name);
 108         if (val instanceof ScriptObject) {
 109             final ScriptObject     valueObj = (ScriptObject)val;
 110             final boolean          strict   = valueObj.isStrictContext();
 111             final Iterator<String> iter     = valueObj.propertyIterator();
 112 
 113             while (iter.hasNext()) {
 114                 final String key        = iter.next();
 115                 final Object newElement = walk(valueObj, key, reviver);
 116 
 117                 if (newElement == ScriptRuntime.UNDEFINED) {
 118                     valueObj.delete(key, strict);
 119                 } else {
 120                     setPropertyValue(valueObj, key, newElement, strict);
 121                 }
 122             }
 123         }
 124 
 125         try {
 126              // Object.class, ScriptFunction.class, ScriptObject.class, String.class, Object.class);
 127              return REVIVER_INVOKER.invokeExact(reviver, holder, JSType.toString(name), val);
 128         } catch(Error|RuntimeException t) {
 129             throw t;
 130         } catch(final Throwable t) {
 131             throw new RuntimeException(t);
 132         }
 133     }
 134 
 135     // Converts IR node to runtime value
 136     private static Object convertNode(final ScriptObject global, final Node node) {
 137         assert global instanceof GlobalObject;
 138 
 139         if (node instanceof LiteralNode) {
 140             // check for array literal
 141             if (node.tokenType() == TokenType.ARRAY) {
 142                 assert node instanceof LiteralNode.ArrayLiteralNode;
 143                 final Node[] elements = ((LiteralNode.ArrayLiteralNode)node).getValue();
 144 
 145                 // NOTE: We cannot use LiteralNode.isNumericArray() here as that
 146                 // method uses symbols of element nodes. Since we don't do lower
 147                 // pass, there won't be any symbols!
 148                 if (isNumericArray(elements)) {
 149                     final double[] values = new double[elements.length];
 150                     int   index = 0;
 151 
 152                     for (final Node elem : elements) {
 153                         values[index++] = JSType.toNumber(convertNode(global, elem));
 154                     }
 155                     return ((GlobalObject)global).wrapAsObject(values);
 156                 }
 157 
 158                 final Object[] values = new Object[elements.length];
 159                 int   index = 0;
 160 
 161                 for (final Node elem : elements) {
 162                     values[index++] = convertNode(global, elem);
 163                 }
 164 
 165                 return ((GlobalObject)global).wrapAsObject(values);
 166             }
 167 
 168             return ((LiteralNode<?>)node).getValue();
 169 
 170         } else if (node instanceof ObjectNode) {
 171             final ObjectNode   objNode  = (ObjectNode) node;
 172             final ScriptObject object   = ((GlobalObject)global).newObject();
 173             final boolean      strict   = global.isStrictContext();
 174             final List<Node>   elements = objNode.getElements();
 175 
 176             for (final Node elem : elements) {
 177                 final PropertyNode pNode     = (PropertyNode) elem;
 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, strict);
 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.rhs()).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, final boolean strict) {
 197         final int index = getArrayIndexNoThrow(name);
 198         if (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, strict);
 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 }