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.lang.reflect.Modifier;
  33 import java.util.Deque;
  34 import java.util.List;
  35 import java.util.Map;
  36 import javax.script.Bindings;
  37 import jdk.internal.dynalink.CallSiteDescriptor;
  38 import jdk.internal.dynalink.linker.ConversionComparator;
  39 import jdk.internal.dynalink.linker.GuardedInvocation;
  40 import jdk.internal.dynalink.linker.GuardingTypeConverterFactory;
  41 import jdk.internal.dynalink.linker.LinkRequest;
  42 import jdk.internal.dynalink.linker.LinkerServices;
  43 import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
  44 import jdk.internal.dynalink.support.Guards;
  45 import jdk.nashorn.api.scripting.JSObject;
  46 import jdk.nashorn.api.scripting.ScriptObjectMirror;
  47 import jdk.nashorn.api.scripting.ScriptUtils;
  48 import jdk.nashorn.internal.objects.NativeArray;
  49 import jdk.nashorn.internal.runtime.Context;
  50 import jdk.nashorn.internal.runtime.JSType;
  51 import jdk.nashorn.internal.runtime.ScriptFunction;
  52 import jdk.nashorn.internal.runtime.ScriptObject;
  53 import jdk.nashorn.internal.runtime.Undefined;
  54 
  55 /**
  56  * This is the main dynamic linker for Nashorn. It is used for linking all {@link ScriptObject} and its subclasses (this
  57  * includes {@link ScriptFunction} and its subclasses) as well as {@link Undefined}.
  58  */
  59 final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory, ConversionComparator {
  60     private static final ClassValue<MethodHandle> ARRAY_CONVERTERS = new ClassValue<MethodHandle>() {
  61         @Override
  62         protected MethodHandle computeValue(Class<?> type) {
  63             return createArrayConverter(type);
  64         }
  65     };
  66 
  67     /**
  68      * Returns true if {@code ScriptObject} is assignable from {@code type}, or it is {@code Undefined}.
  69      */
  70     @Override
  71     public boolean canLinkType(final Class<?> type) {
  72         return canLinkTypeStatic(type);
  73     }
  74 
  75     static boolean canLinkTypeStatic(final Class<?> type) {
  76         return ScriptObject.class.isAssignableFrom(type) || Undefined.class == type;
  77     }
  78 
  79     @Override
  80     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  81         final LinkRequest requestWithoutContext = request.withoutRuntimeContext(); // Nashorn has no runtime context
  82         final Object self = requestWithoutContext.getReceiver();
  83         final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor();
  84 
  85         if (desc.getNameTokenCount() < 2 || !"dyn".equals(desc.getNameToken(CallSiteDescriptor.SCHEME))) {
  86             // We only support standard "dyn:*[:*]" operations
  87             return null;
  88         }
  89 
  90         final GuardedInvocation inv;
  91         if (self instanceof ScriptObject) {
  92             inv = ((ScriptObject)self).lookup(desc, request);
  93         } else if (self instanceof Undefined) {
  94             inv = Undefined.lookup(desc);
  95         } else {
  96             throw new AssertionError(); // Should never reach here.
  97         }
  98 
  99         return Bootstrap.asType(inv, linkerServices, desc);
 100     }
 101 
 102     @Override
 103     public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType) throws Exception {
 104         final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType);
 105         return gi == null ? null : gi.asType(MH.type(targetType, sourceType));
 106     }
 107 
 108     /**
 109      * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType(Class, Class)} that doesn't
 110      * care about adapting the method signature; that's done by the invoking method. Returns either a built-in
 111      * conversion to primitive (or primitive wrapper) Java types or to String, or a just-in-time generated converter to
 112      * a SAM type (if the target type is a SAM type).
 113      * @param sourceType the source type
 114      * @param targetType the target type
 115      * @return a guarded invocation that converts from the source type to the target type.
 116      * @throws Exception if something goes wrong
 117      */
 118     private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception {
 119         final MethodHandle mh = JavaArgumentConverters.getConverter(targetType);
 120         if (mh != null) {
 121             return new GuardedInvocation(mh, canLinkTypeStatic(sourceType) ? null : IS_NASHORN_OR_UNDEFINED_TYPE);
 122         }
 123 
 124         final GuardedInvocation arrayConverter = getArrayConverter(sourceType, targetType);
 125         if(arrayConverter != null) {
 126             return arrayConverter;
 127         }
 128 
 129         final GuardedInvocation mirrorConverter = getMirrorConverter(sourceType, targetType);
 130         if(mirrorConverter != null) {
 131             return mirrorConverter;
 132         }
 133  
 134         return getSamTypeConverter(sourceType, targetType);
 135     }
 136 
 137     /**
 138      * Returns a guarded invocation that converts from a source type that is ScriptFunction, or a subclass or a
 139      * superclass of it) to a SAM type.
 140      * @param sourceType the source type (presumably ScriptFunction or a subclass or a superclass of it)
 141      * @param targetType the target type (presumably a SAM type)
 142      * @return a guarded invocation that converts from the source type to the target SAM type. null is returned if
 143      * either the source type is neither ScriptFunction, nor a subclass, nor a superclass of it, or if the target type
 144      * is not a SAM type.
 145      * @throws Exception if something goes wrong; generally, if there's an issue with creation of the SAM proxy type
 146      * constructor.
 147      */
 148     private static GuardedInvocation getSamTypeConverter(final Class<?> sourceType, final Class<?> targetType) throws Exception {
 149         // If source type is more generic than ScriptFunction class, we'll need to use a guard
 150         final boolean isSourceTypeGeneric = sourceType.isAssignableFrom(ScriptFunction.class);
 151 
 152         if ((isSourceTypeGeneric || ScriptFunction.class.isAssignableFrom(sourceType)) && isAutoConvertibleFromFunction(targetType)) {
 153             final MethodHandle ctor = JavaAdapterFactory.getConstructor(ScriptFunction.class, targetType);
 154             assert ctor != null; // if isAutoConvertibleFromFunction() returned true, then ctor must exist.
 155             return new GuardedInvocation(ctor, isSourceTypeGeneric ? IS_SCRIPT_FUNCTION : null);
 156         }
 157         return null;
 158     }
 159 
 160     /**
 161      * Returns a guarded invocation that converts from a source type that is NativeArray to a Java array or List or
 162      * Deque type.
 163      * @param sourceType the source type (presumably NativeArray a superclass of it)
 164      * @param targetType the target type (presumably an array type, or List or Deque)
 165      * @return a guarded invocation that converts from the source type to the target type. null is returned if
 166      * either the source type is neither NativeArray, nor a superclass of it, or if the target type is not an array
 167      * type, List, or Deque.
 168      */
 169     private static GuardedInvocation getArrayConverter(final Class<?> sourceType, final Class<?> targetType) {
 170         final boolean isSourceTypeNativeArray = sourceType == NativeArray.class;
 171         // If source type is more generic than ScriptFunction class, we'll need to use a guard
 172         final boolean isSourceTypeGeneric = !isSourceTypeNativeArray && sourceType.isAssignableFrom(NativeArray.class);
 173 
 174         if (isSourceTypeNativeArray || isSourceTypeGeneric) {
 175             final MethodHandle guard = isSourceTypeGeneric ? IS_NATIVE_ARRAY : null;
 176             if(targetType.isArray()) {
 177                 return new GuardedInvocation(ARRAY_CONVERTERS.get(targetType), guard);
 178             }
 179             if(targetType == List.class) {
 180                 return new GuardedInvocation(JSType.TO_JAVA_LIST.methodHandle(), guard);
 181             }
 182             if(targetType == Deque.class) {
 183                 return new GuardedInvocation(JSType.TO_JAVA_DEQUE.methodHandle(), guard);
 184             }
 185         }
 186         return null;
 187     }
 188 
 189     private static MethodHandle createArrayConverter(final Class<?> type) {
 190         assert type.isArray();
 191         final MethodHandle converter = MH.insertArguments(JSType.TO_JAVA_ARRAY.methodHandle(), 1, type.getComponentType());
 192         return MH.asType(converter, converter.type().changeReturnType(type));
 193     }
 194 
 195     private static GuardedInvocation getMirrorConverter(Class<?> sourceType, Class<?> targetType) {
 196         // Could've also used (targetType.isAssignableFrom(ScriptObjectMirror.class) && targetType != Object.class) but
 197         // it's probably better to explicitly spell out the supported target types
 198         if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
 199             if(ScriptObject.class.isAssignableFrom(sourceType)) {
 200                 return new GuardedInvocation(CREATE_MIRROR, null);
 201             }
 202             return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
 203         }
 204         return null;
 205     }
 206 
 207     private static boolean isAutoConvertibleFromFunction(final Class<?> clazz) {
 208         return isAbstractClass(clazz) && !ScriptObject.class.isAssignableFrom(clazz) &&
 209                 JavaAdapterFactory.isAutoConvertibleFromFunction(clazz);
 210     }
 211 
 212     /**
 213      * Utility method used by few other places in the code. Tests if the class has the abstract modifier and is not an
 214      * array class. For some reason, array classes have the abstract modifier set in HotSpot JVM, and we don't want to
 215      * treat array classes as abstract.
 216      * @param clazz the inspected class
 217      * @return true if the class is abstract and is not an array type.
 218      */
 219     static boolean isAbstractClass(final Class<?> clazz) {
 220         return Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray();
 221     }
 222 
 223 
 224     @Override
 225     public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
 226         if(sourceType == NativeArray.class) {
 227             // Prefer lists, as they're less costly to create than arrays.
 228             if(isList(targetType1)) {
 229                 if(!isList(targetType2)) {
 230                     return Comparison.TYPE_1_BETTER;
 231                 }
 232             } else if(isList(targetType2)) {
 233                 return Comparison.TYPE_2_BETTER;
 234             }
 235             // Then prefer arrays
 236             if(targetType1.isArray()) {
 237                 if(!targetType2.isArray()) {
 238                     return Comparison.TYPE_1_BETTER;
 239                 }
 240             } else if(targetType2.isArray()) {
 241                 return Comparison.TYPE_2_BETTER;
 242             }
 243         }
 244         if(ScriptObject.class.isAssignableFrom(sourceType)) {
 245             // Prefer interfaces
 246             if(targetType1.isInterface()) {
 247                 if(!targetType2.isInterface()) {
 248                     return Comparison.TYPE_1_BETTER;
 249                 }
 250             } else if(targetType2.isInterface()) {
 251                 return Comparison.TYPE_2_BETTER;
 252             }
 253         }
 254         return Comparison.INDETERMINATE;
 255     }
 256 
 257     private static boolean isList(Class<?> clazz) {
 258         return clazz == List.class || clazz == Deque.class;
 259     }
 260 
 261     private static final MethodHandle IS_SCRIPT_OBJECT = Guards.isInstance(ScriptObject.class, MH.type(Boolean.TYPE, Object.class));
 262     private static final MethodHandle IS_SCRIPT_FUNCTION = Guards.isInstance(ScriptFunction.class, MH.type(Boolean.TYPE, Object.class));
 263     private static final MethodHandle IS_NATIVE_ARRAY = Guards.isOfClass(NativeArray.class, MH.type(Boolean.TYPE, Object.class));
 264 
 265     private static final MethodHandle IS_NASHORN_OR_UNDEFINED_TYPE = findOwnMH("isNashornTypeOrUndefined", Boolean.TYPE, Object.class);
 266     private static final MethodHandle CREATE_MIRROR = findOwnMH("createMirror", Object.class, Object.class);
 267 
 268     @SuppressWarnings("unused")
 269     private static boolean isNashornTypeOrUndefined(final Object obj) {
 270         return obj instanceof ScriptObject || obj instanceof Undefined;
 271     }
 272 
 273     @SuppressWarnings("unused")
 274     private static Object createMirror(final Object obj) {
 275         return ScriptUtils.wrap(obj);
 276     }
 277 
 278     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
 279         return MH.findStatic(MethodHandles.lookup(), NashornLinker.class, name, MH.type(rtype, types));
 280     }
 281 }
 282 
--- EOF ---