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