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.concurrent.Callable;
  30 import jdk.nashorn.internal.objects.Global;
  31 import jdk.nashorn.internal.parser.JSONParser;
  32 import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
  33 import jdk.nashorn.internal.runtime.linker.Bootstrap;
  34 
  35 /**
  36  * Utilities used by "JSON" object implementation.
  37  */
  38 public final class JSONFunctions {
  39     private JSONFunctions() {}
  40 
  41     private static final Object REVIVER_INVOKER = new Object();
  42 
  43     private static MethodHandle getREVIVER_INVOKER() {
  44         return Context.getGlobal().getDynamicInvoker(REVIVER_INVOKER,
  45                 new Callable<MethodHandle>() {
  46                     @Override
  47                     public MethodHandle call() {
  48                         return Bootstrap.createDynamicCallInvoker(Object.class,
  49                             Object.class, Object.class, String.class, Object.class);
  50                     }
  51                 });
  52     }
  53 
  54     /**
  55      * Returns JSON-compatible quoted version of the given string.
  56      *
  57      * @param str String to be quoted
  58      * @return JSON-compatible quoted string
  59      */
  60     public static String quote(final String str) {
  61         return JSONParser.quote(str);
  62     }
  63 
  64     /**
  65      * Parses the given JSON text string and returns object representation.
  66      *
  67      * @param text JSON text to be parsed
  68      * @param reviver  optional value: function that takes two parameters (key, value)
  69      * @return Object representation of JSON text given
  70      */
  71     public static Object parse(final Object text, final Object reviver) {
  72         final String     str    = JSType.toString(text);
  73         final Global     global = Context.getGlobal();
  74         final boolean    dualFields = ((ScriptObject) global).useDualFields();
  75         final JSONParser parser = new JSONParser(str, global, dualFields);
  76         final Object     value;
  77 
  78         try {
  79             value = parser.parse();
  80         } catch (final ParserException e) {
  81             throw ECMAErrors.syntaxError(e, "invalid.json", e.getMessage());
  82         }
  83 
  84         return applyReviver(global, value, 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 Global global, final Object unfiltered, final Object reviver) {
  93         if (Bootstrap.isCallable(reviver)) {
  94             final ScriptObject root = global.newObject();
  95             root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered);
  96             return walk(root, "", 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 Object reviver) {
 103         final Object val = holder.get(name);
 104         if (val instanceof ScriptObject) {
 105             final ScriptObject     valueObj = (ScriptObject)val;
 106             if (valueObj.isArray()) {
 107                 final int length = JSType.toInteger(valueObj.getLength());
 108                 for (int i = 0; i < length; i++) {
 109                     final String key = Integer.toString(i);
 110                     final Object newElement = walk(valueObj, key, reviver);
 111 
 112                     if (newElement == ScriptRuntime.UNDEFINED) {
 113                         valueObj.delete(i, false);
 114                     } else {
 115                         setPropertyValue(valueObj, key, newElement);
 116                     }
 117                 }
 118             } else {
 119                 final String[] keys = valueObj.getOwnKeys(false);
 120                 for (final String key : keys) {
 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);
 127                     }
 128                 }
 129             }
 130         }
 131 
 132         try {
 133              // Object.class, ScriptFunction.class, ScriptObject.class, String.class, Object.class);
 134              return getREVIVER_INVOKER().invokeExact(reviver, (Object)holder, JSType.toString(name), val);
 135         } catch(Error|RuntimeException t) {
 136             throw t;
 137         } catch(final Throwable t) {
 138             throw new RuntimeException(t);
 139         }
 140     }
 141 
 142     // add a new property if does not exist already, or else set old property
 143     private static void setPropertyValue(final ScriptObject sobj, final String name, final Object value) {
 144         final int index = ArrayIndex.getArrayIndex(name);
 145         if (ArrayIndex.isValidArrayIndex(index)) {
 146             // array index key
 147             sobj.defineOwnProperty(index, value);
 148         } else if (sobj.getMap().findProperty(name) != null) {
 149             // pre-existing non-inherited property, call set
 150             sobj.set(name, value, 0);
 151         } else {
 152             // add new property
 153             sobj.addOwnProperty(name, Property.WRITABLE_ENUMERABLE_CONFIGURABLE, value);
 154         }
 155     }
 156 
 157 }