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.concurrent.Callable;
  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.objects.Global;
  37 import jdk.nashorn.internal.parser.JSONParser;
  38 import jdk.nashorn.internal.parser.TokenType;
  39 import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
  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 
  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 JSONParser parser  = new JSONParser(
  81                 new Source("<json>", str),
  82                 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         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             assert global instanceof Global;
 105             final ScriptObject root = global.newObject();
 106             root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered);
 107             return walk(root, "", (ScriptFunction)reviver);
 108         }
 109         return unfiltered;
 110     }
 111 
 112     // This is the abstract "Walk" operation from the spec.
 113     private static Object walk(final ScriptObject holder, final Object name, final ScriptFunction reviver) {
 114         final Object val = holder.get(name);
 115         if (val instanceof ScriptObject) {
 116             final ScriptObject     valueObj = (ScriptObject)val;
 117             final Iterator<String> iter     = valueObj.propertyIterator();
 118 
 119             while (iter.hasNext()) {
 120                 final String key        = iter.next();
 121                 final Object newElement = walk(valueObj, key, reviver);
 122 
 123                 if (newElement == ScriptRuntime.UNDEFINED) {
 124                     valueObj.delete(key, false);
 125                 } else {
 126                     setPropertyValue(valueObj, key, newElement, false);
 127                 }
 128             }
 129         }
 130 
 131         try {
 132              // Object.class, ScriptFunction.class, ScriptObject.class, String.class, Object.class);
 133              return getREVIVER_INVOKER().invokeExact(reviver, holder, JSType.toString(name), val);
 134         } catch(Error|RuntimeException t) {
 135             throw t;
 136         } catch(final Throwable t) {
 137             throw new RuntimeException(t);
 138         }
 139     }
 140 
 141     // Converts IR node to runtime value
 142     private static Object convertNode(final Global global, final Node node) {
 143         assert global instanceof Global;
 144 
 145         if (node instanceof LiteralNode) {
 146             // check for array literal
 147             if (node.tokenType() == TokenType.ARRAY) {
 148                 assert node instanceof LiteralNode.ArrayLiteralNode;
 149                 final Node[] elements = ((LiteralNode.ArrayLiteralNode)node).getValue();
 150 
 151                 // NOTE: We cannot use LiteralNode.isNumericArray() here as that
 152                 // method uses symbols of element nodes. Since we don't do lower
 153                 // pass, there won't be any symbols!
 154                 if (isNumericArray(elements)) {
 155                     final double[] values = new double[elements.length];
 156                     int   index = 0;
 157 
 158                     for (final Node elem : elements) {
 159                         values[index++] = JSType.toNumber(convertNode(global, elem));
 160                     }
 161                     return global.wrapAsObject(values);
 162                 }
 163 
 164                 final Object[] values = new Object[elements.length];
 165                 int   index = 0;
 166 
 167                 for (final Node elem : elements) {
 168                     values[index++] = convertNode(global, elem);
 169                 }
 170 
 171                 return global.wrapAsObject(values);
 172             }
 173 
 174             return ((LiteralNode<?>)node).getValue();
 175 
 176         } else if (node instanceof ObjectNode) {
 177             final ObjectNode   objNode  = (ObjectNode) node;
 178             final ScriptObject object   = global.newObject();
 179 
 180             for (final PropertyNode pNode: objNode.getElements()) {
 181                 final Node         valueNode = pNode.getValue();
 182 
 183                 final String name = pNode.getKeyName();
 184                 final Object value = convertNode(global, valueNode);
 185                 setPropertyValue(object, name, value, false);
 186             }
 187 
 188             return object;
 189         } else if (node instanceof UnaryNode) {
 190             // UnaryNode used only to represent negative number JSON value
 191             final UnaryNode unaryNode = (UnaryNode)node;
 192             return -((LiteralNode<?>)unaryNode.rhs()).getNumber();
 193         } else {
 194             return null;
 195         }
 196     }
 197 
 198     // add a new property if does not exist already, or else set old property
 199     private static void setPropertyValue(final ScriptObject sobj, final String name, final Object value, final boolean strict) {
 200         final int index = ArrayIndex.getArrayIndex(name);
 201         if (ArrayIndex.isValidArrayIndex(index)) {
 202             // array index key
 203             sobj.defineOwnProperty(index, value);
 204         } else if (sobj.getMap().findProperty(name) != null) {
 205             // pre-existing non-inherited property, call set
 206             sobj.set(name, value, strict);
 207         } else {
 208             // add new property
 209             sobj.addOwnProperty(name, Property.WRITABLE_ENUMERABLE_CONFIGURABLE, value);
 210         }
 211     }
 212 
 213     // does the given IR node represent a numeric array?
 214     private static boolean isNumericArray(final Node[] values) {
 215         for (final Node node : values) {
 216             if (node instanceof LiteralNode && ((LiteralNode<?>)node).getValue() instanceof Number) {
 217                 continue;
 218             }
 219             return false;
 220         }
 221         return true;
 222     }
 223 }