aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/api/scripting/ScriptUtils.java
blob: 29d03db4f4b7d4ef8f6fb41f2c825f60461fcd32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.api.scripting;

import java.lang.invoke.MethodHandle;
import jdk.internal.dynalink.beans.StaticClass;
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;

/**
 * Utilities that are to be called from script code.
 */
public final class ScriptUtils {
    private ScriptUtils() {}

    /**
     * Returns AST as JSON compatible string. This is used to
     * implement "parse" function in resources/parse.js script.
     *
     * @param code code to be parsed
     * @param name name of the code source (used for location)
     * @param includeLoc tells whether to include location information for nodes or not
     * @return JSON string representation of AST of the supplied code
     */
    public static String parse(final String code, final String name, final boolean includeLoc) {
        return ScriptRuntime.parse(code, name, includeLoc);
    }

    /**
     * Method which converts javascript types to java types for the
     * String.format method (jrunscript function sprintf).
     *
     * @param format a format string
     * @param args arguments referenced by the format specifiers in format
     * @return a formatted string
     */
    public static String format(final String format, final Object[] args) {
        return Formatter.format(format, args);
    }

    /**
     * Create a wrapper function that calls {@code func} synchronized on {@code sync} or, if that is undefined,
     * {@code self}. Used to implement "sync" function in resources/mozilla_compat.js.
     *
     * @param func the function to invoke
     * @param sync the object to synchronize on
     * @return a synchronizing wrapper function
     */
    public static Object makeSynchronizedFunction(final ScriptFunction func, final Object sync) {
        return func.makeSynchronizedFunction(sync);
    }

    /**
     * Make a script object mirror on given object if needed.
     *
     * @param obj object to be wrapped
     * @return wrapped object
     */
    public static Object wrap(final Object obj) {
        if (obj instanceof ScriptObject) {
            return ScriptObjectMirror.wrap(obj, Context.getGlobal());
        }

        return obj;
    }

    /**
     * Unwrap a script object mirror if needed.
     *
     * @param obj object to be unwrapped
     * @return unwrapped object
     */
    public static Object unwrap(final Object obj) {
        if (obj instanceof ScriptObjectMirror) {
            return ScriptObjectMirror.unwrap(obj, Context.getGlobal());
        }

        return obj;
    }

    /**
     * Wrap an array of object to script object mirrors if needed.
     *
     * @param args array to be unwrapped
     * @return wrapped array
     */
    public static Object[] wrapArray(final Object[] args) {
        if (args == null || args.length == 0) {
            return args;
        }

        return ScriptObjectMirror.wrapArray(args, Context.getGlobal());
    }

    /**
     * Unwrap an array of script object mirrors if needed.
     *
     * @param args array to be unwrapped
     * @return unwrapped array
     */
    public static Object[] unwrapArray(final Object[] args) {
        if (args == null || args.length == 0) {
            return args;
        }

        return ScriptObjectMirror.unwrapArray(args, Context.getGlobal());
    }

    /**
     * Convert the given object to the given type.
     *
     * @param obj object to be converted
     * @param type destination type to convert to
     * @return converted object
     */
    public static Object convert(final Object obj, final Object type) {
        if (obj == null) {
            return null;
        }

        final Class<?> clazz;
        if (type instanceof Class) {
            clazz = (Class<?>)type;
        } else if (type instanceof StaticClass) {
            clazz = ((StaticClass)type).getRepresentedClass();
        } else {
            throw new IllegalArgumentException("type expected");
        }

        final LinkerServices linker = Bootstrap.getLinkerServices();
        final MethodHandle converter = linker.getTypeConverter(obj.getClass(),  clazz);
        if (converter == null) {
            // no supported conversion!
            throw new UnsupportedOperationException("conversion not supported");
        }

        try {
            return converter.invoke(obj);
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    }
}