Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.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.text.Collator;89import java.util.ArrayList;90import java.util.Collections;91import java.util.Iterator;92import java.util.LinkedList;93import java.util.List;94import jdk.internal.dynalink.CallSiteDescriptor;95import jdk.internal.dynalink.beans.ApplicableOverloadedMethods.ApplicabilityTest;96import jdk.internal.dynalink.linker.LinkerServices;97import jdk.internal.dynalink.support.TypeUtilities;9899/**100* Represents a group of {@link SingleDynamicMethod} objects that represents all overloads of a particular name (or all101* constructors) for a particular class. Correctly handles overload resolution, variable arity methods, and caller102* sensitive methods within the overloads.103*104* @author Attila Szegedi105*/106class OverloadedDynamicMethod extends DynamicMethod {107/**108* Holds a list of all methods.109*/110private final LinkedList<SingleDynamicMethod> methods;111private final ClassLoader classLoader;112113/**114* Creates a new overloaded dynamic method.115*116* @param clazz the class this method belongs to117* @param name the name of the method118*/119OverloadedDynamicMethod(final Class<?> clazz, final String name) {120this(new LinkedList<SingleDynamicMethod>(), clazz.getClassLoader(), getClassAndMethodName(clazz, name));121}122123private OverloadedDynamicMethod(final LinkedList<SingleDynamicMethod> methods, final ClassLoader classLoader, final String name) {124super(name);125this.methods = methods;126this.classLoader = classLoader;127}128129@Override130SingleDynamicMethod getMethodForExactParamTypes(final String paramTypes) {131final LinkedList<SingleDynamicMethod> matchingMethods = new LinkedList<>();132for(final SingleDynamicMethod method: methods) {133final SingleDynamicMethod matchingMethod = method.getMethodForExactParamTypes(paramTypes);134if(matchingMethod != null) {135matchingMethods.add(matchingMethod);136}137}138switch(matchingMethods.size()) {139case 0: {140return null;141}142case 1: {143return matchingMethods.getFirst();144}145default: {146throw new BootstrapMethodError("Can't choose among " + matchingMethods + " for argument types "147+ paramTypes + " for method " + getName());148}149}150}151152@Override153public MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) {154final MethodType callSiteType = callSiteDescriptor.getMethodType();155// First, find all methods applicable to the call site by subtyping (JLS 15.12.2.2)156final ApplicableOverloadedMethods subtypingApplicables = getApplicables(callSiteType,157ApplicableOverloadedMethods.APPLICABLE_BY_SUBTYPING);158// Next, find all methods applicable by method invocation conversion to the call site (JLS 15.12.2.3).159final ApplicableOverloadedMethods methodInvocationApplicables = getApplicables(callSiteType,160ApplicableOverloadedMethods.APPLICABLE_BY_METHOD_INVOCATION_CONVERSION);161// Finally, find all methods applicable by variable arity invocation. (JLS 15.12.2.4).162final ApplicableOverloadedMethods variableArityApplicables = getApplicables(callSiteType,163ApplicableOverloadedMethods.APPLICABLE_BY_VARIABLE_ARITY);164165// Find the methods that are maximally specific based on the call site signature166List<SingleDynamicMethod> maximallySpecifics = subtypingApplicables.findMaximallySpecificMethods();167if(maximallySpecifics.isEmpty()) {168maximallySpecifics = methodInvocationApplicables.findMaximallySpecificMethods();169if(maximallySpecifics.isEmpty()) {170maximallySpecifics = variableArityApplicables.findMaximallySpecificMethods();171}172}173174// Now, get a list of the rest of the methods; those that are *not* applicable to the call site signature based175// on JLS rules. As paradoxical as that might sound, we have to consider these for dynamic invocation, as they176// might match more concrete types passed in invocations. That's why we provisionally call them "invokables".177// This is typical for very generic signatures at call sites. Typical example: call site specifies178// (Object, Object), and we have a method whose parameter types are (String, int). None of the JLS applicability179// rules will trigger, but we must consider the method, as it can be the right match for a concrete invocation.180@SuppressWarnings({ "unchecked", "rawtypes" })181final List<SingleDynamicMethod> invokables = (List)methods.clone();182invokables.removeAll(subtypingApplicables.getMethods());183invokables.removeAll(methodInvocationApplicables.getMethods());184invokables.removeAll(variableArityApplicables.getMethods());185for(final Iterator<SingleDynamicMethod> it = invokables.iterator(); it.hasNext();) {186final SingleDynamicMethod m = it.next();187if(!isApplicableDynamically(linkerServices, callSiteType, m)) {188it.remove();189}190}191192// If no additional methods can apply at invocation time, and there's more than one maximally specific method193// based on call site signature, that is a link-time ambiguity. In a static scenario, javac would report an194// ambiguity error.195if(invokables.isEmpty() && maximallySpecifics.size() > 1) {196throw new BootstrapMethodError("Can't choose among " + maximallySpecifics + " for argument types "197+ callSiteType);198}199200// Merge them all.201invokables.addAll(maximallySpecifics);202switch(invokables.size()) {203case 0: {204// No overloads can ever match the call site type205return null;206}207case 1: {208// Very lucky, we ended up with a single candidate method handle based on the call site signature; we209// can link it very simply by delegating to the SingleDynamicMethod.210return invokables.iterator().next().getInvocation(callSiteDescriptor, linkerServices);211}212default: {213// We have more than one candidate. We have no choice but to link to a method that resolves overloads on214// every invocation (alternatively, we could opportunistically link the one method that resolves for the215// current arguments, but we'd need to install a fairly complex guard for that and when it'd fail, we'd216// go back all the way to candidate selection. Note that we're resolving any potential caller sensitive217// methods here to their handles, as the OverloadedMethod instance is specific to a call site, so it218// has an already determined Lookup.219final List<MethodHandle> methodHandles = new ArrayList<>(invokables.size());220final MethodHandles.Lookup lookup = callSiteDescriptor.getLookup();221for(final SingleDynamicMethod method: invokables) {222methodHandles.add(method.getTarget(lookup));223}224return new OverloadedMethod(methodHandles, this, callSiteType, linkerServices).getInvoker();225}226}227228}229230@Override231public boolean contains(final SingleDynamicMethod m) {232for(final SingleDynamicMethod method: methods) {233if(method.contains(m)) {234return true;235}236}237return false;238}239240@Override241public boolean isConstructor() {242assert !methods.isEmpty();243return methods.getFirst().isConstructor();244}245246@Override247public String toString() {248// First gather the names and sort them. This makes it consistent and easier to read.249final List<String> names = new ArrayList<>(methods.size());250int len = 0;251for (final SingleDynamicMethod m: methods) {252final String name = m.getName();253len += name.length();254names.add(name);255}256// Case insensitive sorting, so e.g. "Object" doesn't come before "boolean".257final Collator collator = Collator.getInstance();258collator.setStrength(Collator.SECONDARY);259Collections.sort(names, collator);260261final String className = getClass().getName();262// Class name length + length of signatures + 2 chars/per signature for indentation and newline +263// 3 for brackets and initial newline264final int totalLength = className.length() + len + 2 * names.size() + 3;265final StringBuilder b = new StringBuilder(totalLength);266b.append('[').append(className).append('\n');267for(final String name: names) {268b.append(' ').append(name).append('\n');269}270b.append(']');271assert b.length() == totalLength;272return b.toString();273};274275ClassLoader getClassLoader() {276return classLoader;277}278279private static boolean isApplicableDynamically(final LinkerServices linkerServices, final MethodType callSiteType,280final SingleDynamicMethod m) {281final MethodType methodType = m.getMethodType();282final boolean varArgs = m.isVarArgs();283final int fixedArgLen = methodType.parameterCount() - (varArgs ? 1 : 0);284final int callSiteArgLen = callSiteType.parameterCount();285286// Arity checks287if(varArgs) {288if(callSiteArgLen < fixedArgLen) {289return false;290}291} else if(callSiteArgLen != fixedArgLen) {292return false;293}294295// Fixed arguments type checks, starting from 1, as receiver type doesn't participate296for(int i = 1; i < fixedArgLen; ++i) {297if(!isApplicableDynamically(linkerServices, callSiteType.parameterType(i), methodType.parameterType(i))) {298return false;299}300}301if(!varArgs) {302// Not vararg; both arity and types matched.303return true;304}305306final Class<?> varArgArrayType = methodType.parameterType(fixedArgLen);307final Class<?> varArgType = varArgArrayType.getComponentType();308309if(fixedArgLen == callSiteArgLen - 1) {310// Exactly one vararg; check both array type matching and array component type matching.311final Class<?> callSiteArgType = callSiteType.parameterType(fixedArgLen);312return isApplicableDynamically(linkerServices, callSiteArgType, varArgArrayType)313|| isApplicableDynamically(linkerServices, callSiteArgType, varArgType);314}315316// Either zero, or more than one vararg; check if all actual vararg types match the vararg array component type.317for(int i = fixedArgLen; i < callSiteArgLen; ++i) {318if(!isApplicableDynamically(linkerServices, callSiteType.parameterType(i), varArgType)) {319return false;320}321}322323return true;324}325326private static boolean isApplicableDynamically(final LinkerServices linkerServices, final Class<?> callSiteType,327final Class<?> methodType) {328return TypeUtilities.isPotentiallyConvertible(callSiteType, methodType)329|| linkerServices.canConvert(callSiteType, methodType);330}331332private ApplicableOverloadedMethods getApplicables(final MethodType callSiteType, final ApplicabilityTest test) {333return new ApplicableOverloadedMethods(methods, callSiteType, test);334}335336/**337* Add a method to this overloaded method's set.338*339* @param method a method to add340*/341public void addMethod(final SingleDynamicMethod method) {342assert constructorFlagConsistent(method);343methods.add(method);344}345346private boolean constructorFlagConsistent(final SingleDynamicMethod method) {347return methods.isEmpty()? true : (methods.getFirst().isConstructor() == method.isConstructor());348}349}350351352