JSONFunctions.java revision 1033:c1f651636d9c
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
26package jdk.nashorn.internal.runtime;
27
28import static jdk.nashorn.internal.runtime.Source.sourceFor;
29
30import java.lang.invoke.MethodHandle;
31import java.util.Iterator;
32import java.util.concurrent.Callable;
33import jdk.nashorn.internal.ir.LiteralNode;
34import jdk.nashorn.internal.ir.Node;
35import jdk.nashorn.internal.ir.ObjectNode;
36import jdk.nashorn.internal.ir.PropertyNode;
37import jdk.nashorn.internal.ir.UnaryNode;
38import jdk.nashorn.internal.objects.Global;
39import jdk.nashorn.internal.parser.JSONParser;
40import jdk.nashorn.internal.parser.TokenType;
41import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
42import jdk.nashorn.internal.runtime.linker.Bootstrap;
43
44/**
45 * Utilities used by "JSON" object implementation.
46 */
47public final class JSONFunctions {
48    private JSONFunctions() {}
49
50    private static final Object REVIVER_INVOKER = new Object();
51
52    private static MethodHandle getREVIVER_INVOKER() {
53        return Context.getGlobal().getDynamicInvoker(REVIVER_INVOKER,
54                new Callable<MethodHandle>() {
55                    @Override
56                    public MethodHandle call() {
57                        return Bootstrap.createDynamicInvoker("dyn:call", Object.class,
58                            ScriptFunction.class, ScriptObject.class, String.class, Object.class);
59                    }
60                });
61    }
62
63    /**
64     * Returns JSON-compatible quoted version of the given string.
65     *
66     * @param str String to be quoted
67     * @return JSON-compatible quoted string
68     */
69    public static String quote(final String str) {
70        return JSONParser.quote(str);
71    }
72
73    /**
74     * Parses the given JSON text string and returns object representation.
75     *
76     * @param text JSON text to be parsed
77     * @param reviver  optional value: function that takes two parameters (key, value)
78     * @return Object representation of JSON text given
79     */
80    public static Object parse(final Object text, final Object reviver) {
81        final String     str     = JSType.toString(text);
82        final JSONParser parser  = new JSONParser(sourceFor("<json>", str), 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        final 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            final ScriptObject root = 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);
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 Global global, final Node node) {
142        if (node instanceof LiteralNode) {
143            // check for array literal
144            if (node.tokenType() == TokenType.ARRAY) {
145                assert node instanceof LiteralNode.ArrayLiteralNode;
146                final Node[] elements = ((LiteralNode.ArrayLiteralNode)node).getValue();
147
148                // NOTE: We cannot use LiteralNode.isNumericArray() here as that
149                // method uses symbols of element nodes. Since we don't do lower
150                // pass, there won't be any symbols!
151                if (isNumericArray(elements)) {
152                    final double[] values = new double[elements.length];
153                    int   index = 0;
154
155                    for (final Node elem : elements) {
156                        values[index++] = JSType.toNumber(convertNode(global, elem));
157                    }
158                    return global.wrapAsObject(values);
159                }
160
161                final Object[] values = new Object[elements.length];
162                int   index = 0;
163
164                for (final Node elem : elements) {
165                    values[index++] = convertNode(global, elem);
166                }
167
168                return global.wrapAsObject(values);
169            }
170
171            return ((LiteralNode<?>)node).getValue();
172
173        } else if (node instanceof ObjectNode) {
174            final ObjectNode   objNode  = (ObjectNode) node;
175            final ScriptObject object   = global.newObject();
176
177            for (final PropertyNode pNode: objNode.getElements()) {
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);
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.getExpression()).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) {
197        final int index = ArrayIndex.getArrayIndex(name);
198        if (ArrayIndex.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, 0);
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}
221