src/jdk/nashorn/internal/runtime/JSONFunctions.java

Print this page




  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




  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