aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/runtime/linker/JavaArgumentConverters.java
blob: e16564402267d2246fa43be51ecadf4185b64d13 (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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
 * 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.internal.runtime.linker;

import static jdk.nashorn.internal.lookup.Lookup.MH;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.JSType.isString;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import java.util.Map;
import jdk.internal.dynalink.support.TypeUtilities;
import jdk.nashorn.internal.runtime.ConsString;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptObject;

/**
 * Utility class shared by {@code NashornLinker} and {@code NashornPrimitiveLinker} for converting JS values to Java
 * types.
 */
final class JavaArgumentConverters {

    private static final MethodHandle TO_BOOLEAN        = findOwnMH("toBoolean", Boolean.class, Object.class);
    private static final MethodHandle TO_STRING         = findOwnMH("toString", String.class, Object.class);
    private static final MethodHandle TO_DOUBLE         = findOwnMH("toDouble", Double.class, Object.class);
    private static final MethodHandle TO_NUMBER         = findOwnMH("toNumber", Number.class, Object.class);
    private static final MethodHandle TO_LONG           = findOwnMH("toLong", Long.class, Object.class);
    private static final MethodHandle TO_LONG_PRIMITIVE = findOwnMH("toLongPrimitive", long.class, Object.class);
    private static final MethodHandle TO_CHAR           = findOwnMH("toChar", Character.class, Object.class);
    private static final MethodHandle TO_CHAR_PRIMITIVE = findOwnMH("toCharPrimitive", char.class, Object.class);

    private JavaArgumentConverters() {
    }

    static MethodHandle getConverter(final Class<?> targetType) {
        return CONVERTERS.get(targetType);
    }

    @SuppressWarnings("unused")
    private static Boolean toBoolean(final Object obj) {
        if (obj instanceof Boolean) {
            return (Boolean) obj;
        }

        if (obj == null) {
            // NOTE: FindBugs complains here about the NP_BOOLEAN_RETURN_NULL pattern: we're returning null from a
            // method that has a return type of Boolean, as it is worried about a NullPointerException if there's a
            // conversion to a primitive boolean. We know what we're doing, though. We're using a separate method when
            // we're converting Object to a primitive boolean - see how the CONVERTERS map is populated. We specifically
            // want to have null and Undefined to be converted to a (Boolean)null when being passed to a Java method
            // that expects a Boolean argument.
            // TODO: if/when we're allowed to use FindBugs at build time, we can use annotations to disable this warning
            return null;
        }

        if (obj == UNDEFINED) {
            // NOTE: same reasoning for FindBugs NP_BOOLEAN_RETURN_NULL warning as in the preceding comment.
            return null;
        }

        if (obj instanceof Number) {
            final double num = ((Number) obj).doubleValue();
            return num != 0 && !Double.isNaN(num);
        }

        if (isString(obj)) {
            return ((CharSequence) obj).length() > 0;
        }

        if (obj instanceof ScriptObject) {
            return true;
        }

        throw assertUnexpectedType(obj);
    }

    private static Character toChar(final Object o) {
        if (o == null) {
            return null;
        }

        if (o instanceof Number) {
            final int ival = ((Number)o).intValue();
            if (ival >= Character.MIN_VALUE && ival <= Character.MAX_VALUE) {
                return Character.valueOf((char) ival);
            }

            throw typeError("cant.convert.number.to.char");
        }

        final String s = toString(o);
        if (s == null) {
            return null;
        }

        if (s.length() != 1) {
            throw typeError("cant.convert.string.to.char");
        }

        return s.charAt(0);
    }

    static char toCharPrimitive(final Object obj0) {
        final Character c = toChar(obj0);
        return c == null ? (char)0 : c;
    }

    // Almost identical to ScriptRuntime.toString, but returns null for null instead of the string "null".
    static String toString(final Object obj) {
        return obj == null ? null : JSType.toString(obj);
    }

    @SuppressWarnings("unused")
    private static Double toDouble(final Object obj0) {
        // TODO - Order tests for performance.
        for (Object obj = obj0; ;) {
            if (obj == null) {
                return null;
            } else if (obj instanceof Double) {
                return (Double) obj;
            } else if (obj instanceof Number) {
                return ((Number)obj).doubleValue();
            } else if (obj instanceof String) {
                return JSType.toNumber((String) obj);
            } else if (obj instanceof ConsString) {
                return JSType.toNumber(obj.toString());
            } else if (obj instanceof Boolean) {
                return (Boolean) obj ? 1 : +0.0;
            } else if (obj instanceof ScriptObject) {
                obj = JSType.toPrimitive(obj, Number.class);
                continue;
            } else if (obj == UNDEFINED) {
                return Double.NaN;
            }
            throw assertUnexpectedType(obj);
        }
    }

    @SuppressWarnings("unused")
    private static Number toNumber(final Object obj0) {
        // TODO - Order tests for performance.
        for (Object obj = obj0; ;) {
            if (obj == null) {
                return null;
            } else if (obj instanceof Number) {
                return (Number) obj;
            } else if (obj instanceof String) {
                return JSType.toNumber((String) obj);
            } else if (obj instanceof ConsString) {
                return JSType.toNumber(obj.toString());
            } else if (obj instanceof Boolean) {
                return (Boolean) obj ? 1 : +0.0;
            } else if (obj instanceof ScriptObject) {
                obj = JSType.toPrimitive(obj, Number.class);
                continue;
            } else if (obj == UNDEFINED) {
                return Double.NaN;
            }
            throw assertUnexpectedType(obj);
        }
    }

    private static Long toLong(final Object obj0) {
        // TODO - Order tests for performance.
        for (Object obj = obj0; ;) {
            if (obj == null) {
                return null;
            } else if (obj instanceof Long) {
                return (Long) obj;
            } else if (obj instanceof Integer) {
                return ((Integer)obj).longValue();
            } else if (obj instanceof Double) {
                final Double d = (Double)obj;
                if(Double.isInfinite(d.doubleValue())) {
                    return 0L;
                }
                return d.longValue();
            } else if (obj instanceof Float) {
                final Float f = (Float)obj;
                if(Float.isInfinite(f.floatValue())) {
                    return 0L;
                }
                return f.longValue();
            } else if (obj instanceof Number) {
                return ((Number)obj).longValue();
            } else if (isString(obj)) {
                return JSType.toLong(obj);
            } else if (obj instanceof Boolean) {
                return (Boolean)obj ? 1L : 0L;
            } else if (obj instanceof ScriptObject) {
                obj = JSType.toPrimitive(obj, Number.class);
                continue;
            } else if (obj == UNDEFINED) {
                return null; // null or 0L?
            }
            throw assertUnexpectedType(obj);
        }
    }

    private static AssertionError assertUnexpectedType(final Object obj) {
        return new AssertionError("Unexpected type" + obj.getClass().getName() + ". Guards should have prevented this");
    }

    @SuppressWarnings("unused")
    private static long toLongPrimitive(final Object obj0) {
        final Long l = toLong(obj0);
        return l == null ? 0L : l;
    }

    private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
        return MH.findStatic(MethodHandles.lookup(), JavaArgumentConverters.class, name, MH.type(rtype, types));
    }

    private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>();

    static {
        CONVERTERS.put(Number.class, TO_NUMBER);
        CONVERTERS.put(String.class, TO_STRING);

        CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle());
        CONVERTERS.put(Boolean.class, TO_BOOLEAN);

        CONVERTERS.put(char.class, TO_CHAR_PRIMITIVE);
        CONVERTERS.put(Character.class, TO_CHAR);

        CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle());
        CONVERTERS.put(Double.class, TO_DOUBLE);

        CONVERTERS.put(long.class, TO_LONG_PRIMITIVE);
        CONVERTERS.put(Long.class, TO_LONG);

        putLongConverter(Byte.class);
        putLongConverter(Short.class);
        putLongConverter(Integer.class);
        putDoubleConverter(Float.class);

    }

    private static void putDoubleConverter(final Class<?> targetType) {
        final Class<?> primitive = TypeUtilities.getPrimitiveType(targetType);
        CONVERTERS.put(primitive,  MH.explicitCastArguments(JSType.TO_NUMBER.methodHandle(), JSType.TO_NUMBER.methodHandle().type().changeReturnType(primitive)));
        CONVERTERS.put(targetType, MH.filterReturnValue(TO_DOUBLE, findOwnMH(primitive.getName() + "Value", targetType, Double.class)));
    }

    private static void putLongConverter(final Class<?> targetType) {
        final Class<?> primitive = TypeUtilities.getPrimitiveType(targetType);
        CONVERTERS.put(primitive,  MH.explicitCastArguments(TO_LONG_PRIMITIVE, TO_LONG_PRIMITIVE.type().changeReturnType(primitive)));
        CONVERTERS.put(targetType, MH.filterReturnValue(TO_LONG, findOwnMH(primitive.getName() + "Value", targetType, Long.class)));
    }

    @SuppressWarnings("unused")
    private static Byte byteValue(final Long l) {
        return l == null ? null : l.byteValue();
    }

    @SuppressWarnings("unused")
    private static Short shortValue(final Long l) {
        return l == null ? null : l.shortValue();
    }

    @SuppressWarnings("unused")
    private static Integer intValue(final Long l) {
        return l == null ? null : l.intValue();
    }

    @SuppressWarnings("unused")
    private static Float floatValue(final Double d) {
        return d == null ? null : d.floatValue();
    }

}