Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java
48600 views
/*1* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file, and Oracle licenses the original version of this file under the BSD30* license:31*/32/*33Copyright 2009-2013 Attila Szegedi3435Licensed under both the Apache License, Version 2.0 (the "Apache License")36and the BSD License (the "BSD License"), with licensee being free to37choose either of the two at their discretion.3839You may not use this file except in compliance with either the Apache40License or the BSD License.4142If you choose to use this file in compliance with the Apache License, the43following notice applies to you:4445You may obtain a copy of the Apache License at4647http://www.apache.org/licenses/LICENSE-2.04849Unless required by applicable law or agreed to in writing, software50distributed under the License is distributed on an "AS IS" BASIS,51WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or52implied. See the License for the specific language governing53permissions and limitations under the License.5455If you choose to use this file in compliance with the BSD License, the56following notice applies to you:5758Redistribution and use in source and binary forms, with or without59modification, are permitted provided that the following conditions are60met:61* Redistributions of source code must retain the above copyright62notice, this list of conditions and the following disclaimer.63* Redistributions in binary form must reproduce the above copyright64notice, this list of conditions and the following disclaimer in the65documentation and/or other materials provided with the distribution.66* Neither the name of the copyright holder nor the names of67contributors may be used to endorse or promote products derived from68this software without specific prior written permission.6970THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS71IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED72TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A73PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER74BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR75CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF76SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR77BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,78WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR79OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF80ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.81*/8283package jdk.internal.dynalink.beans;8485import java.lang.invoke.MethodHandle;86import java.lang.invoke.MethodHandles;87import java.lang.invoke.MethodType;88import java.lang.reflect.Array;89import java.util.StringTokenizer;90import jdk.internal.dynalink.CallSiteDescriptor;91import jdk.internal.dynalink.linker.LinkerServices;92import jdk.internal.dynalink.support.Guards;93import jdk.internal.dynalink.support.Lookup;9495/**96* Base class for dynamic methods that dispatch to a single target Java method or constructor. Handles adaptation of the97* target method to a call site type (including mapping variable arity methods to a call site signature with different98* arity).99* @author Attila Szegedi100*/101abstract class SingleDynamicMethod extends DynamicMethod {102103private static final MethodHandle CAN_CONVERT_TO = Lookup.findOwnStatic(MethodHandles.lookup(), "canConvertTo", boolean.class, LinkerServices.class, Class.class, Object.class);104105SingleDynamicMethod(final String name) {106super(name);107}108109/**110* Returns true if this method is variable arity.111* @return true if this method is variable arity.112*/113abstract boolean isVarArgs();114115/**116* Returns this method's native type.117* @return this method's native type.118*/119abstract MethodType getMethodType();120121/**122* Given a specified lookup, returns a method handle to this method's target.123* @param lookup the lookup to use.124* @return the handle to this method's target method.125*/126abstract MethodHandle getTarget(MethodHandles.Lookup lookup);127128@Override129MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) {130return getInvocation(getTarget(callSiteDescriptor.getLookup()), callSiteDescriptor.getMethodType(),131linkerServices);132}133134@Override135SingleDynamicMethod getMethodForExactParamTypes(final String paramTypes) {136return typeMatchesDescription(paramTypes, getMethodType()) ? this : null;137}138139@Override140boolean contains(final SingleDynamicMethod method) {141return getMethodType().parameterList().equals(method.getMethodType().parameterList());142}143144static String getMethodNameWithSignature(final MethodType type, final String methodName, final boolean withReturnType) {145final String typeStr = type.toString();146final int retTypeIndex = typeStr.lastIndexOf(')') + 1;147int secondParamIndex = typeStr.indexOf(',') + 1;148if(secondParamIndex == 0) {149secondParamIndex = retTypeIndex - 1;150}151final StringBuilder b = new StringBuilder();152if (withReturnType) {153b.append(typeStr, retTypeIndex, typeStr.length()).append(' ');154}155return b.append(methodName).append('(').append(typeStr, secondParamIndex, retTypeIndex).toString();156}157158/**159* Given a method handle and a call site type, adapts the method handle to the call site type. Performs type160* conversions as needed using the specified linker services, and in case that the method handle is a vararg161* collector, matches it to the arity of the call site. The type of the return value is only changed if it can be162* converted using a conversion that loses neither precision nor magnitude, see163* {@link LinkerServices#asTypeLosslessReturn(MethodHandle, MethodType)}.164* @param target the method handle to adapt165* @param callSiteType the type of the call site166* @param linkerServices the linker services used for type conversions167* @return the adapted method handle.168*/169static MethodHandle getInvocation(final MethodHandle target, final MethodType callSiteType, final LinkerServices linkerServices) {170final MethodHandle filteredTarget = linkerServices.filterInternalObjects(target);171final MethodType methodType = filteredTarget.type();172final int paramsLen = methodType.parameterCount();173final boolean varArgs = target.isVarargsCollector();174final MethodHandle fixTarget = varArgs ? filteredTarget.asFixedArity() : filteredTarget;175final int fixParamsLen = varArgs ? paramsLen - 1 : paramsLen;176final int argsLen = callSiteType.parameterCount();177if(argsLen < fixParamsLen) {178// Less actual arguments than number of fixed declared arguments; can't invoke.179return null;180}181// Method handle has the same number of fixed arguments as the call site type182if(argsLen == fixParamsLen) {183// Method handle that matches the number of actual arguments as the number of fixed arguments184final MethodHandle matchedMethod;185if(varArgs) {186// If vararg, add a zero-length array of the expected type as the last argument to signify no variable187// arguments.188matchedMethod = MethodHandles.insertArguments(fixTarget, fixParamsLen, Array.newInstance(189methodType.parameterType(fixParamsLen).getComponentType(), 0));190} else {191// Otherwise, just use the method192matchedMethod = fixTarget;193}194return createConvertingInvocation(matchedMethod, linkerServices, callSiteType);195}196197// What's below only works for varargs198if(!varArgs) {199return null;200}201202final Class<?> varArgType = methodType.parameterType(fixParamsLen);203// Handle a somewhat sinister corner case: caller passes exactly one argument in the vararg position, and we204// must handle both a prepacked vararg array as well as a genuine 1-long vararg sequence.205if(argsLen == paramsLen) {206final Class<?> callSiteLastArgType = callSiteType.parameterType(fixParamsLen);207if(varArgType.isAssignableFrom(callSiteLastArgType)) {208// Call site signature guarantees we'll always be passed a single compatible array; just link directly209// to the method, introducing necessary conversions. Also, preserve it being a variable arity method.210return createConvertingInvocation(filteredTarget, linkerServices, callSiteType).asVarargsCollector(211callSiteLastArgType);212}213214// This method handle takes the single argument and packs it into a newly allocated single-element array. It215// will be used when the incoming argument can't be converted to the vararg array type (the "vararg packer"216// method).217final MethodHandle varArgCollectingInvocation = createConvertingInvocation(collectArguments(fixTarget,218argsLen), linkerServices, callSiteType);219220// Is call site type assignable from an array type (e.g. Object:int[], or Object[]:String[])221final boolean isAssignableFromArray = callSiteLastArgType.isAssignableFrom(varArgType);222// Do we have a custom conversion that can potentially convert the call site type to an array?223final boolean isCustomConvertible = linkerServices.canConvert(callSiteLastArgType, varArgType);224if(!isAssignableFromArray && !isCustomConvertible) {225// Call site signature guarantees the argument can definitely not be converted to an array (i.e. it is226// primitive), and no conversion can help with it either. Link immediately to a vararg-packing method227// handle.228return varArgCollectingInvocation;229}230231// This method handle employs language-specific conversions to convert the last argument into an array of232// vararg type.233final MethodHandle arrayConvertingInvocation = createConvertingInvocation(MethodHandles.filterArguments(234fixTarget, fixParamsLen, linkerServices.getTypeConverter(callSiteLastArgType, varArgType)),235linkerServices, callSiteType);236237// This method handle determines whether the value can be converted to the array of vararg type using a238// language-specific conversion.239final MethodHandle canConvertArgToArray = MethodHandles.insertArguments(CAN_CONVERT_TO, 0, linkerServices,240varArgType);241242// This one adjusts the previous one for the location of the argument and the call site type.243final MethodHandle canConvertLastArgToArray = MethodHandles.dropArguments(canConvertArgToArray, 0,244MethodType.genericMethodType(fixParamsLen).parameterList()).asType(callSiteType.changeReturnType(boolean.class));245246// This one takes the previous ones and combines them into a method handle that converts the argument into247// a vararg array when it can, otherwise falls back to the vararg packer.248final MethodHandle convertToArrayWhenPossible = MethodHandles.guardWithTest(canConvertLastArgToArray,249arrayConvertingInvocation, varArgCollectingInvocation);250251if(isAssignableFromArray) {252return MethodHandles.guardWithTest(253// Is incoming parameter already a compatible array?254Guards.isInstance(varArgType, fixParamsLen, callSiteType),255// Yes: just pass it to the method256createConvertingInvocation(fixTarget, linkerServices, callSiteType),257// No: either go through a custom conversion, or if it is not possible, go directly to the258// vararg packer.259isCustomConvertible ? convertToArrayWhenPossible : varArgCollectingInvocation);260}261262// Just do the custom conversion with fallback to the vararg packer logic.263assert isCustomConvertible;264return convertToArrayWhenPossible;265}266267// Remaining case: more than one vararg.268return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType);269}270271@SuppressWarnings("unused")272private static boolean canConvertTo(final LinkerServices linkerServices, final Class<?> to, final Object obj) {273return obj == null ? false : linkerServices.canConvert(obj.getClass(), to);274}275276/**277* Creates a method handle out of the original target that will collect the varargs for the exact component type of278* the varArg array. Note that this will nicely trigger language-specific type converters for exactly those varargs279* for which it is necessary when later passed to linkerServices.convertArguments().280*281* @param target the original method handle282* @param parameterCount the total number of arguments in the new method handle283* @return a collecting method handle284*/285static MethodHandle collectArguments(final MethodHandle target, final int parameterCount) {286final MethodType methodType = target.type();287final int fixParamsLen = methodType.parameterCount() - 1;288final Class<?> arrayType = methodType.parameterType(fixParamsLen);289return target.asCollector(arrayType, parameterCount - fixParamsLen);290}291292private static MethodHandle createConvertingInvocation(final MethodHandle sizedMethod,293final LinkerServices linkerServices, final MethodType callSiteType) {294return linkerServices.asTypeLosslessReturn(sizedMethod, callSiteType);295}296297private static boolean typeMatchesDescription(final String paramTypes, final MethodType type) {298final StringTokenizer tok = new StringTokenizer(paramTypes, ", ");299for(int i = 1; i < type.parameterCount(); ++i) { // i = 1 as we ignore the receiver300if(!(tok.hasMoreTokens() && typeNameMatches(tok.nextToken(), type.parameterType(i)))) {301return false;302}303}304return !tok.hasMoreTokens();305}306307private static boolean typeNameMatches(final String typeName, final Class<?> type) {308return typeName.equals(typeName.indexOf('.') == -1 ? type.getSimpleName() : type.getCanonicalName());309}310}311312313