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