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.linker;
27 
28 import static jdk.nashorn.internal.lookup.Lookup.MH;
29 
30 import java.lang.invoke.MethodHandle;
31 import java.lang.invoke.MethodHandles;
32 import java.util.function.Supplier;
33 import jdk.dynalink.linker.ConversionComparator;
34 import jdk.dynalink.linker.GuardedInvocation;
35 import jdk.dynalink.linker.GuardingTypeConverterFactory;
36 import jdk.dynalink.linker.LinkRequest;
37 import jdk.dynalink.linker.LinkerServices;
38 import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
39 import jdk.dynalink.linker.support.TypeUtilities;
40 import jdk.nashorn.internal.objects.Global;
41 import jdk.nashorn.internal.runtime.ConsString;
42 import jdk.nashorn.internal.runtime.JSType;
43 import jdk.nashorn.internal.runtime.ScriptRuntime;
44 import jdk.nashorn.internal.runtime.Symbol;
45 
46 /**
47  * Internal linker for String, Boolean, and Number objects, only ever used by Nashorn engine and not exposed to other
48  * engines. It is used for treatment of strings, boolean, and numbers as JavaScript primitives. Also provides ECMAScript
49  * primitive type conversions for these types when linking to Java methods.
50  */
51 final class NashornPrimitiveLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory, ConversionComparator {
52     private static final GuardedInvocation VOID_TO_OBJECT =
53             new GuardedInvocation(MethodHandles.constant(Object.class, ScriptRuntime.UNDEFINED));
54 
55     @Override
canLinkType(final Class<?> type)56     public boolean canLinkType(final Class<?> type) {
57         return canLinkTypeStatic(type);
58     }
59 
canLinkTypeStatic(final Class<?> type)60     private static boolean canLinkTypeStatic(final Class<?> type) {
61         return type == String.class || type == Boolean.class || type == ConsString.class || type == Integer.class
62                 || type == Double.class || type == Float.class || type == Short.class || type == Byte.class
63                 || type == Symbol.class;
64     }
65 
66     @Override
getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices)67     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices)
68             throws Exception {
69         final Object self = request.getReceiver();
70         return Bootstrap.asTypeSafeReturn(Global.primitiveLookup(request, self), linkerServices, request.getCallSiteDescriptor());
71     }
72 
73     /**
74      * This implementation of type converter factory will pretty much allow implicit conversions of anything to anything
75      * else that's allowed among JavaScript primitive types (string to number, boolean to string, etc.)
76      * @param sourceType the type to convert from
77      * @param targetType the type to convert to
78      * @return a conditional converter from source to target type
79      */
80     @Override
convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier)81     public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) {
82         final MethodHandle mh = JavaArgumentConverters.getConverter(targetType);
83         if (mh == null) {
84             if(targetType == Object.class && sourceType == void.class) {
85                 return VOID_TO_OBJECT;
86             }
87             return null;
88         }
89 
90         return new GuardedInvocation(mh, canLinkTypeStatic(sourceType) ? null : GUARD_PRIMITIVE).asType(mh.type().changeParameterType(0, sourceType));
91     }
92 
93     /**
94      * Implements the somewhat involved prioritization of JavaScript primitive types conversions. Instead of explaining
95      * it here in prose, just follow the source code comments.
96      * @param sourceType the source type to convert from
97      * @param targetType1 one candidate target type
98      * @param targetType2 another candidate target type
99      * @return one of {@link jdk.dynalink.linker.ConversionComparator.Comparison} values signifying which
100      * target type should be favored for conversion.
101      */
102     @Override
compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2)103     public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
104         final Class<?> wrapper1 = getWrapperTypeOrSelf(targetType1);
105         if (sourceType == wrapper1) {
106             // Source type exactly matches target 1
107             return Comparison.TYPE_1_BETTER;
108         }
109         final Class<?> wrapper2 = getWrapperTypeOrSelf(targetType2);
110         if (sourceType == wrapper2) {
111             // Source type exactly matches target 2
112             return Comparison.TYPE_2_BETTER;
113         }
114 
115         if (Number.class.isAssignableFrom(sourceType)) {
116             // If exactly one of the targets is a number, pick it.
117             if (Number.class.isAssignableFrom(wrapper1)) {
118                 if (!Number.class.isAssignableFrom(wrapper2)) {
119                     return Comparison.TYPE_1_BETTER;
120                 }
121             } else if (Number.class.isAssignableFrom(wrapper2)) {
122                 return Comparison.TYPE_2_BETTER;
123             }
124 
125             // If exactly one of the targets is a character, pick it. Numbers can be reasonably converted to chars using
126             // the UTF-16 values.
127             if (Character.class == wrapper1) {
128                 return Comparison.TYPE_1_BETTER;
129             } else if (Character.class == wrapper2) {
130                 return Comparison.TYPE_2_BETTER;
131             }
132 
133             // For all other cases, we fall through to the next if statement - not that we repeat the condition in it
134             // too so if we entered this branch, we'll enter the below if statement too.
135         }
136 
137         if (sourceType == String.class || sourceType == Boolean.class || Number.class.isAssignableFrom(sourceType)) {
138             // Treat wrappers as primitives.
139             final Class<?> primitiveType1 = getPrimitiveTypeOrSelf(targetType1);
140             final Class<?> primitiveType2 = getPrimitiveTypeOrSelf(targetType2);
141             // Basically, choose the widest possible primitive type. (First "if" returning TYPE_2_BETTER is correct;
142             // when faced with a choice between double and int, choose double).
143             if (TypeUtilities.isMethodInvocationConvertible(primitiveType1, primitiveType2)) {
144                 return Comparison.TYPE_2_BETTER;
145             } else if (TypeUtilities.isMethodInvocationConvertible(primitiveType2, primitiveType1)) {
146                 return Comparison.TYPE_1_BETTER;
147             }
148             // Ok, at this point we're out of possible number conversions, so try strings. A String can represent any
149             // value without loss, so if one of the potential targets is string, go for it.
150             if (targetType1 == String.class) {
151                 return Comparison.TYPE_1_BETTER;
152             }
153             if (targetType2 == String.class) {
154                 return Comparison.TYPE_2_BETTER;
155             }
156         }
157 
158         return Comparison.INDETERMINATE;
159     }
160 
getPrimitiveTypeOrSelf(final Class<?> type)161     private static Class<?> getPrimitiveTypeOrSelf(final Class<?> type) {
162         final Class<?> primitive = TypeUtilities.getPrimitiveType(type);
163         return primitive == null ? type : primitive;
164     }
165 
getWrapperTypeOrSelf(final Class<?> type)166     private static Class<?> getWrapperTypeOrSelf(final Class<?> type) {
167         final Class<?> wrapper = TypeUtilities.getWrapperType(type);
168         return wrapper == null ? type : wrapper;
169     }
170 
171     @SuppressWarnings("unused")
isJavaScriptPrimitive(final Object o)172     private static boolean isJavaScriptPrimitive(final Object o) {
173         return JSType.isString(o) || o instanceof Boolean || JSType.isNumber(o) || o == null || o instanceof Symbol;
174     }
175 
176     private static final MethodHandle GUARD_PRIMITIVE = findOwnMH("isJavaScriptPrimitive", boolean.class, Object.class);
177 
findOwnMH(final String name, final Class<?> rtype, final Class<?>... types)178     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
179         return MH.findStatic(MethodHandles.lookup(), NashornPrimitiveLinker.class, name, MH.type(rtype, types));
180     }
181 }
182