src/jdk/internal/dynalink/support/TypeUtilities.java

changeset 0
b1a7da25b547
child 952
6d5471a497fb
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/jdk/internal/dynalink/support/TypeUtilities.java	Wed Apr 27 01:36:41 2016 +0800
     1.3 @@ -0,0 +1,442 @@
     1.4 +/*
     1.5 + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +/*
    1.30 + * This file is available under and governed by the GNU General Public
    1.31 + * License version 2 only, as published by the Free Software Foundation.
    1.32 + * However, the following notice accompanied the original version of this
    1.33 + * file, and Oracle licenses the original version of this file under the BSD
    1.34 + * license:
    1.35 + */
    1.36 +/*
    1.37 +   Copyright 2009-2013 Attila Szegedi
    1.38 +
    1.39 +   Licensed under both the Apache License, Version 2.0 (the "Apache License")
    1.40 +   and the BSD License (the "BSD License"), with licensee being free to
    1.41 +   choose either of the two at their discretion.
    1.42 +
    1.43 +   You may not use this file except in compliance with either the Apache
    1.44 +   License or the BSD License.
    1.45 +
    1.46 +   If you choose to use this file in compliance with the Apache License, the
    1.47 +   following notice applies to you:
    1.48 +
    1.49 +       You may obtain a copy of the Apache License at
    1.50 +
    1.51 +           http://www.apache.org/licenses/LICENSE-2.0
    1.52 +
    1.53 +       Unless required by applicable law or agreed to in writing, software
    1.54 +       distributed under the License is distributed on an "AS IS" BASIS,
    1.55 +       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    1.56 +       implied. See the License for the specific language governing
    1.57 +       permissions and limitations under the License.
    1.58 +
    1.59 +   If you choose to use this file in compliance with the BSD License, the
    1.60 +   following notice applies to you:
    1.61 +
    1.62 +       Redistribution and use in source and binary forms, with or without
    1.63 +       modification, are permitted provided that the following conditions are
    1.64 +       met:
    1.65 +       * Redistributions of source code must retain the above copyright
    1.66 +         notice, this list of conditions and the following disclaimer.
    1.67 +       * Redistributions in binary form must reproduce the above copyright
    1.68 +         notice, this list of conditions and the following disclaimer in the
    1.69 +         documentation and/or other materials provided with the distribution.
    1.70 +       * Neither the name of the copyright holder nor the names of
    1.71 +         contributors may be used to endorse or promote products derived from
    1.72 +         this software without specific prior written permission.
    1.73 +
    1.74 +       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    1.75 +       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    1.76 +       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    1.77 +       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
    1.78 +       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    1.79 +       CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    1.80 +       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
    1.81 +       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
    1.82 +       WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
    1.83 +       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
    1.84 +       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1.85 +*/
    1.86 +
    1.87 +package jdk.internal.dynalink.support;
    1.88 +
    1.89 +import java.util.ArrayList;
    1.90 +import java.util.Collection;
    1.91 +import java.util.Collections;
    1.92 +import java.util.HashMap;
    1.93 +import java.util.HashSet;
    1.94 +import java.util.IdentityHashMap;
    1.95 +import java.util.Iterator;
    1.96 +import java.util.List;
    1.97 +import java.util.Map;
    1.98 +import java.util.Set;
    1.99 +
   1.100 +/**
   1.101 + * Various static utility methods for testing type relationships.
   1.102 + *
   1.103 + * @author Attila Szegedi
   1.104 + */
   1.105 +public class TypeUtilities {
   1.106 +    static final Class<Object> OBJECT_CLASS = Object.class;
   1.107 +
   1.108 +    private TypeUtilities() {
   1.109 +    }
   1.110 +
   1.111 +    /**
   1.112 +     * Given two types represented by c1 and c2, returns a type that is their most specific common superclass or
   1.113 +     * superinterface.
   1.114 +     *
   1.115 +     * @param c1 one type
   1.116 +     * @param c2 another type
   1.117 +     * @return their most common superclass or superinterface. If they have several unrelated superinterfaces as their
   1.118 +     * most specific common type, or the types themselves are completely unrelated interfaces, {@link java.lang.Object}
   1.119 +     * is returned.
   1.120 +     */
   1.121 +    public static Class<?> getMostSpecificCommonType(Class<?> c1, Class<?> c2) {
   1.122 +        if(c1 == c2) {
   1.123 +            return c1;
   1.124 +        }
   1.125 +        Class<?> c3 = c2;
   1.126 +        if(c3.isPrimitive()) {
   1.127 +            if(c3 == Byte.TYPE)
   1.128 +                c3 = Byte.class;
   1.129 +            else if(c3 == Short.TYPE)
   1.130 +                c3 = Short.class;
   1.131 +            else if(c3 == Character.TYPE)
   1.132 +                c3 = Character.class;
   1.133 +            else if(c3 == Integer.TYPE)
   1.134 +                c3 = Integer.class;
   1.135 +            else if(c3 == Float.TYPE)
   1.136 +                c3 = Float.class;
   1.137 +            else if(c3 == Long.TYPE)
   1.138 +                c3 = Long.class;
   1.139 +            else if(c3 == Double.TYPE)
   1.140 +                c3 = Double.class;
   1.141 +        }
   1.142 +        Set<Class<?>> a1 = getAssignables(c1, c3);
   1.143 +        Set<Class<?>> a2 = getAssignables(c3, c1);
   1.144 +        a1.retainAll(a2);
   1.145 +        if(a1.isEmpty()) {
   1.146 +            // Can happen when at least one of the arguments is an interface,
   1.147 +            // as they don't have Object at the root of their hierarchy.
   1.148 +            return Object.class;
   1.149 +        }
   1.150 +        // Gather maximally specific elements. Yes, there can be more than one
   1.151 +        // thank to interfaces. I.e., if you call this method for String.class
   1.152 +        // and Number.class, you'll have Comparable, Serializable, and Object
   1.153 +        // as maximal elements.
   1.154 +        List<Class<?>> max = new ArrayList<>();
   1.155 +        outer: for(Class<?> clazz: a1) {
   1.156 +            for(Iterator<Class<?>> maxiter = max.iterator(); maxiter.hasNext();) {
   1.157 +                Class<?> maxClazz = maxiter.next();
   1.158 +                if(isSubtype(maxClazz, clazz)) {
   1.159 +                    // It can't be maximal, if there's already a more specific
   1.160 +                    // maximal than it.
   1.161 +                    continue outer;
   1.162 +                }
   1.163 +                if(isSubtype(clazz, maxClazz)) {
   1.164 +                    // If it's more specific than a currently maximal element,
   1.165 +                    // that currently maximal is no longer a maximal.
   1.166 +                    maxiter.remove();
   1.167 +                }
   1.168 +            }
   1.169 +            // If we get here, no current maximal is more specific than the
   1.170 +            // current class, so it is considered maximal as well
   1.171 +            max.add(clazz);
   1.172 +        }
   1.173 +        if(max.size() > 1) {
   1.174 +            return OBJECT_CLASS;
   1.175 +        }
   1.176 +        return max.get(0);
   1.177 +    }
   1.178 +
   1.179 +    private static Set<Class<?>> getAssignables(Class<?> c1, Class<?> c2) {
   1.180 +        Set<Class<?>> s = new HashSet<>();
   1.181 +        collectAssignables(c1, c2, s);
   1.182 +        return s;
   1.183 +    }
   1.184 +
   1.185 +    private static void collectAssignables(Class<?> c1, Class<?> c2, Set<Class<?>> s) {
   1.186 +        if(c1.isAssignableFrom(c2)) {
   1.187 +            s.add(c1);
   1.188 +        }
   1.189 +        Class<?> sc = c1.getSuperclass();
   1.190 +        if(sc != null) {
   1.191 +            collectAssignables(sc, c2, s);
   1.192 +        }
   1.193 +        Class<?>[] itf = c1.getInterfaces();
   1.194 +        for(int i = 0; i < itf.length; ++i) {
   1.195 +            collectAssignables(itf[i], c2, s);
   1.196 +        }
   1.197 +    }
   1.198 +
   1.199 +    private static final Map<Class<?>, Class<?>> WRAPPER_TYPES = createWrapperTypes();
   1.200 +    private static final Map<Class<?>, Class<?>> PRIMITIVE_TYPES = invertMap(WRAPPER_TYPES);
   1.201 +    private static final Map<String, Class<?>> PRIMITIVE_TYPES_BY_NAME = createClassNameMapping(WRAPPER_TYPES.keySet());
   1.202 +
   1.203 +    private static Map<Class<?>, Class<?>> createWrapperTypes() {
   1.204 +        final Map<Class<?>, Class<?>> wrapperTypes = new IdentityHashMap<>(8);
   1.205 +        wrapperTypes.put(Boolean.TYPE, Boolean.class);
   1.206 +        wrapperTypes.put(Byte.TYPE, Byte.class);
   1.207 +        wrapperTypes.put(Character.TYPE, Character.class);
   1.208 +        wrapperTypes.put(Short.TYPE, Short.class);
   1.209 +        wrapperTypes.put(Integer.TYPE, Integer.class);
   1.210 +        wrapperTypes.put(Long.TYPE, Long.class);
   1.211 +        wrapperTypes.put(Float.TYPE, Float.class);
   1.212 +        wrapperTypes.put(Double.TYPE, Double.class);
   1.213 +        return Collections.unmodifiableMap(wrapperTypes);
   1.214 +    }
   1.215 +
   1.216 +    private static Map<String, Class<?>> createClassNameMapping(Collection<Class<?>> classes) {
   1.217 +        final Map<String, Class<?>> map = new HashMap<>();
   1.218 +        for(Class<?> clazz: classes) {
   1.219 +            map.put(clazz.getName(), clazz);
   1.220 +        }
   1.221 +        return map;
   1.222 +    }
   1.223 +
   1.224 +    private static <K, V> Map<V, K> invertMap(Map<K, V> map) {
   1.225 +        final Map<V, K> inverted = new IdentityHashMap<>(map.size());
   1.226 +        for(Map.Entry<K, V> entry: map.entrySet()) {
   1.227 +            inverted.put(entry.getValue(), entry.getKey());
   1.228 +        }
   1.229 +        return Collections.unmodifiableMap(inverted);
   1.230 +    }
   1.231 +
   1.232 +    /**
   1.233 +     * Determines whether one type can be converted to another type using a method invocation conversion, as per JLS 5.3
   1.234 +     * "Method Invocation Conversion". This is basically all conversions allowed by subtyping (see
   1.235 +     * {@link #isSubtype(Class, Class)}) as well as boxing conversion (JLS 5.1.7) optionally followed by widening
   1.236 +     * reference conversion and unboxing conversion (JLS 5.1.8) optionally followed by widening primitive conversion.
   1.237 +     *
   1.238 +     * @param callSiteType the parameter type at the call site
   1.239 +     * @param methodType the parameter type in the method declaration
   1.240 +     * @return true if callSiteType is method invocation convertible to the methodType.
   1.241 +     */
   1.242 +    public static boolean isMethodInvocationConvertible(Class<?> callSiteType, Class<?> methodType) {
   1.243 +        if(methodType.isAssignableFrom(callSiteType)) {
   1.244 +            return true;
   1.245 +        }
   1.246 +        if(callSiteType.isPrimitive()) {
   1.247 +            if(methodType.isPrimitive()) {
   1.248 +                return isProperPrimitiveSubtype(callSiteType, methodType);
   1.249 +            }
   1.250 +            // Boxing + widening reference conversion
   1.251 +            return methodType.isAssignableFrom(WRAPPER_TYPES.get(callSiteType));
   1.252 +        }
   1.253 +        if(methodType.isPrimitive()) {
   1.254 +            final Class<?> unboxedCallSiteType = PRIMITIVE_TYPES.get(callSiteType);
   1.255 +            return unboxedCallSiteType != null
   1.256 +                    && (unboxedCallSiteType == methodType || isProperPrimitiveSubtype(unboxedCallSiteType, methodType));
   1.257 +        }
   1.258 +        return false;
   1.259 +    }
   1.260 +
   1.261 +    /**
   1.262 +     * Determines whether one type can be potentially converted to another type at runtime. Allows a conversion between
   1.263 +     * any subtype and supertype in either direction, and also allows a conversion between any two primitive types, as
   1.264 +     * well as between any primitive type and any reference type that can hold a boxed primitive.
   1.265 +     *
   1.266 +     * @param callSiteType the parameter type at the call site
   1.267 +     * @param methodType the parameter type in the method declaration
   1.268 +     * @return true if callSiteType is potentially convertible to the methodType.
   1.269 +     */
   1.270 +    public static boolean isPotentiallyConvertible(Class<?> callSiteType, Class<?> methodType) {
   1.271 +        // Widening or narrowing reference conversion
   1.272 +        if(methodType.isAssignableFrom(callSiteType) || callSiteType.isAssignableFrom(methodType)) {
   1.273 +            return true;
   1.274 +        }
   1.275 +        if(callSiteType.isPrimitive()) {
   1.276 +            // Allow any conversion among primitives, as well as from any
   1.277 +            // primitive to any type that can receive a boxed primitive.
   1.278 +            // TODO: narrow this a bit, i.e. allow, say, boolean to Character?
   1.279 +            // MethodHandles.convertArguments() allows it, so we might need to
   1.280 +            // too.
   1.281 +            return methodType.isPrimitive() || isAssignableFromBoxedPrimitive(methodType);
   1.282 +        }
   1.283 +        if(methodType.isPrimitive()) {
   1.284 +            // Allow conversion from any reference type that can contain a
   1.285 +            // boxed primitive to any primitive.
   1.286 +            // TODO: narrow this a bit too?
   1.287 +            return isAssignableFromBoxedPrimitive(callSiteType);
   1.288 +        }
   1.289 +        return false;
   1.290 +    }
   1.291 +
   1.292 +    /**
   1.293 +     * Determines whether one type is a subtype of another type, as per JLS 4.10 "Subtyping". Note: this is not strict
   1.294 +     * or proper subtype, therefore true is also returned for identical types; to be completely precise, it allows
   1.295 +     * identity conversion (JLS 5.1.1), widening primitive conversion (JLS 5.1.2) and widening reference conversion (JLS
   1.296 +     * 5.1.5).
   1.297 +     *
   1.298 +     * @param subType the supposed subtype
   1.299 +     * @param superType the supposed supertype of the subtype
   1.300 +     * @return true if subType can be converted by identity conversion, widening primitive conversion, or widening
   1.301 +     * reference conversion to superType.
   1.302 +     */
   1.303 +    public static boolean isSubtype(Class<?> subType, Class<?> superType) {
   1.304 +        // Covers both JLS 4.10.2 "Subtyping among Class and Interface Types"
   1.305 +        // and JLS 4.10.3 "Subtyping among Array Types", as well as primitive
   1.306 +        // type identity.
   1.307 +        if(superType.isAssignableFrom(subType)) {
   1.308 +            return true;
   1.309 +        }
   1.310 +        // JLS 4.10.1 "Subtyping among Primitive Types". Note we don't test for
   1.311 +        // identity, as identical types were taken care of in the
   1.312 +        // isAssignableFrom test. As per 4.10.1, the supertype relation is as
   1.313 +        // follows:
   1.314 +        // double > float
   1.315 +        // float > long
   1.316 +        // long > int
   1.317 +        // int > short
   1.318 +        // int > char
   1.319 +        // short > byte
   1.320 +        if(superType.isPrimitive() && subType.isPrimitive()) {
   1.321 +            return isProperPrimitiveSubtype(subType, superType);
   1.322 +        }
   1.323 +        return false;
   1.324 +    }
   1.325 +
   1.326 +    /**
   1.327 +     * Returns true if a supposed primitive subtype is a proper subtype ( meaning, subtype and not identical) of the
   1.328 +     * supposed primitive supertype
   1.329 +     *
   1.330 +     * @param subType the supposed subtype
   1.331 +     * @param superType the supposed supertype
   1.332 +     * @return true if subType is a proper (not identical to) primitive subtype of the superType
   1.333 +     */
   1.334 +    private static boolean isProperPrimitiveSubtype(Class<?> subType, Class<?> superType) {
   1.335 +        if(superType == boolean.class || subType == boolean.class) {
   1.336 +            return false;
   1.337 +        }
   1.338 +        if(subType == byte.class) {
   1.339 +            return superType != char.class;
   1.340 +        }
   1.341 +        if(subType == char.class) {
   1.342 +            return superType != short.class && superType != byte.class;
   1.343 +        }
   1.344 +        if(subType == short.class) {
   1.345 +            return superType != char.class && superType != byte.class;
   1.346 +        }
   1.347 +        if(subType == int.class) {
   1.348 +            return superType == long.class || superType == float.class || superType == double.class;
   1.349 +        }
   1.350 +        if(subType == long.class) {
   1.351 +            return superType == float.class || superType == double.class;
   1.352 +        }
   1.353 +        if(subType == float.class) {
   1.354 +            return superType == double.class;
   1.355 +        }
   1.356 +        return false;
   1.357 +    }
   1.358 +
   1.359 +    private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPES = createWrapperToPrimitiveTypes();
   1.360 +
   1.361 +    private static Map<Class<?>, Class<?>> createWrapperToPrimitiveTypes() {
   1.362 +        final Map<Class<?>, Class<?>> classes = new IdentityHashMap<>();
   1.363 +        classes.put(Void.class, Void.TYPE);
   1.364 +        classes.put(Boolean.class, Boolean.TYPE);
   1.365 +        classes.put(Byte.class, Byte.TYPE);
   1.366 +        classes.put(Character.class, Character.TYPE);
   1.367 +        classes.put(Short.class, Short.TYPE);
   1.368 +        classes.put(Integer.class, Integer.TYPE);
   1.369 +        classes.put(Long.class, Long.TYPE);
   1.370 +        classes.put(Float.class, Float.TYPE);
   1.371 +        classes.put(Double.class, Double.TYPE);
   1.372 +        return classes;
   1.373 +    }
   1.374 +
   1.375 +    private static final Set<Class<?>> PRIMITIVE_WRAPPER_TYPES = createPrimitiveWrapperTypes();
   1.376 +
   1.377 +    private static Set<Class<?>> createPrimitiveWrapperTypes() {
   1.378 +        final Map<Class<?>, Class<?>> classes = new IdentityHashMap<>();
   1.379 +        addClassHierarchy(classes, Boolean.class);
   1.380 +        addClassHierarchy(classes, Byte.class);
   1.381 +        addClassHierarchy(classes, Character.class);
   1.382 +        addClassHierarchy(classes, Short.class);
   1.383 +        addClassHierarchy(classes, Integer.class);
   1.384 +        addClassHierarchy(classes, Long.class);
   1.385 +        addClassHierarchy(classes, Float.class);
   1.386 +        addClassHierarchy(classes, Double.class);
   1.387 +        return classes.keySet();
   1.388 +    }
   1.389 +
   1.390 +    private static void addClassHierarchy(Map<Class<?>, Class<?>> map, Class<?> clazz) {
   1.391 +        if(clazz == null) {
   1.392 +            return;
   1.393 +        }
   1.394 +        map.put(clazz, clazz);
   1.395 +        addClassHierarchy(map, clazz.getSuperclass());
   1.396 +        for(Class<?> itf: clazz.getInterfaces()) {
   1.397 +            addClassHierarchy(map, itf);
   1.398 +        }
   1.399 +    }
   1.400 +
   1.401 +    /**
   1.402 +     * Returns true if the class can be assigned from any boxed primitive.
   1.403 +     *
   1.404 +     * @param clazz the class
   1.405 +     * @return true if the class can be assigned from any boxed primitive. Basically, it is true if the class is any
   1.406 +     * primitive wrapper class, or a superclass or superinterface of any primitive wrapper class.
   1.407 +     */
   1.408 +    private static boolean isAssignableFromBoxedPrimitive(Class<?> clazz) {
   1.409 +        return PRIMITIVE_WRAPPER_TYPES.contains(clazz);
   1.410 +    }
   1.411 +
   1.412 +    /**
   1.413 +     * Given a name of a primitive type (except "void"), returns the class representing it. I.e. when invoked with
   1.414 +     * "int", returns {@link Integer#TYPE}.
   1.415 +     * @param name the name of the primitive type
   1.416 +     * @return the class representing the primitive type, or null if the name does not correspond to a primitive type
   1.417 +     * or is "void".
   1.418 +     */
   1.419 +    public static Class<?> getPrimitiveTypeByName(String name) {
   1.420 +        return PRIMITIVE_TYPES_BY_NAME.get(name);
   1.421 +    }
   1.422 +
   1.423 +    /**
   1.424 +     * When passed a class representing a wrapper for a primitive type, returns the class representing the corresponding
   1.425 +     * primitive type. I.e. calling it with {@code Integer.class} will return {@code Integer.TYPE}. If passed a class
   1.426 +     * that is not a wrapper for primitive type, returns null.
   1.427 +     * @param wrapperType the class object representing a wrapper for a primitive type
   1.428 +     * @return the class object representing the primitive type, or null if the passed class is not a primitive wrapper.
   1.429 +     */
   1.430 +    public static Class<?> getPrimitiveType(Class<?> wrapperType) {
   1.431 +        return WRAPPER_TO_PRIMITIVE_TYPES.get(wrapperType);
   1.432 +    }
   1.433 +
   1.434 +
   1.435 +    /**
   1.436 +     * When passed a class representing a primitive type, returns the class representing the corresponding
   1.437 +     * wrapper type. I.e. calling it with {@code int.class} will return {@code Integer.class}. If passed a class
   1.438 +     * that is not a primitive type, returns null.
   1.439 +     * @param primitiveType the class object representing a primitive type
   1.440 +     * @return the class object representing the wrapper type, or null if the passed class is not a primitive.
   1.441 +     */
   1.442 +    public static Class<?> getWrapperType(Class<?> primitiveType) {
   1.443 +        return WRAPPER_TYPES.get(primitiveType);
   1.444 +    }
   1.445 +}

mercurial