rt/emul/compact/src/main/java/java/lang/invoke/AbstractValidatingLambdaMetafactory.java
branchjdk8
changeset 1675 cd50c1894ce5
parent 1674 eca8e9c3ec3e
child 1678 35daab73e225
     1.1 --- a/rt/emul/compact/src/main/java/java/lang/invoke/AbstractValidatingLambdaMetafactory.java	Sun Aug 17 20:09:05 2014 +0200
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,375 +0,0 @@
     1.4 -/*
     1.5 - * Copyright (c) 2012, 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 -package java.lang.invoke;
    1.29 -
    1.30 -import sun.invoke.util.Wrapper;
    1.31 -
    1.32 -import static sun.invoke.util.Wrapper.forPrimitiveType;
    1.33 -import static sun.invoke.util.Wrapper.forWrapperType;
    1.34 -import static sun.invoke.util.Wrapper.isWrapperType;
    1.35 -
    1.36 -/**
    1.37 - * Abstract implementation of a lambda metafactory which provides parameter
    1.38 - * unrolling and input validation.
    1.39 - *
    1.40 - * @see LambdaMetafactory
    1.41 - */
    1.42 -/* package */ abstract class AbstractValidatingLambdaMetafactory {
    1.43 -
    1.44 -    /*
    1.45 -     * For context, the comments for the following fields are marked in quotes
    1.46 -     * with their values, given this program:
    1.47 -     * interface II<T> {  Object foo(T x); }
    1.48 -     * interface JJ<R extends Number> extends II<R> { }
    1.49 -     * class CC {  String impl(int i) { return "impl:"+i; }}
    1.50 -     * class X {
    1.51 -     *     public static void main(String[] args) {
    1.52 -     *         JJ<Integer> iii = (new CC())::impl;
    1.53 -     *         System.out.printf(">>> %s\n", iii.foo(44));
    1.54 -     * }}
    1.55 -     */
    1.56 -    final Class<?> targetClass;               // The class calling the meta-factory via invokedynamic "class X"
    1.57 -    final MethodType invokedType;             // The type of the invoked method "(CC)II"
    1.58 -    final Class<?> samBase;                   // The type of the returned instance "interface JJ"
    1.59 -    final String samMethodName;               // Name of the SAM method "foo"
    1.60 -    final MethodType samMethodType;           // Type of the SAM method "(Object)Object"
    1.61 -    final MethodHandle implMethod;            // Raw method handle for the implementation method
    1.62 -    final MethodHandleInfo implInfo;          // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]"
    1.63 -    final int implKind;                       // Invocation kind for implementation "5"=invokevirtual
    1.64 -    final boolean implIsInstanceMethod;       // Is the implementation an instance method "true"
    1.65 -    final Class<?> implDefiningClass;         // Type defining the implementation "class CC"
    1.66 -    final MethodType implMethodType;          // Type of the implementation method "(int)String"
    1.67 -    final MethodType instantiatedMethodType;  // Instantiated erased functional interface method type "(Integer)Object"
    1.68 -    final boolean isSerializable;             // Should the returned instance be serializable
    1.69 -    final Class<?>[] markerInterfaces;        // Additional marker interfaces to be implemented
    1.70 -    final MethodType[] additionalBridges;     // Signatures of additional methods to bridge
    1.71 -
    1.72 -
    1.73 -    /**
    1.74 -     * Meta-factory constructor.
    1.75 -     *
    1.76 -     * @param caller Stacked automatically by VM; represents a lookup context
    1.77 -     *               with the accessibility privileges of the caller.
    1.78 -     * @param invokedType Stacked automatically by VM; the signature of the
    1.79 -     *                    invoked method, which includes the expected static
    1.80 -     *                    type of the returned lambda object, and the static
    1.81 -     *                    types of the captured arguments for the lambda.  In
    1.82 -     *                    the event that the implementation method is an
    1.83 -     *                    instance method, the first argument in the invocation
    1.84 -     *                    signature will correspond to the receiver.
    1.85 -     * @param samMethodName Name of the method in the functional interface to
    1.86 -     *                      which the lambda or method reference is being
    1.87 -     *                      converted, represented as a String.
    1.88 -     * @param samMethodType Type of the method in the functional interface to
    1.89 -     *                      which the lambda or method reference is being
    1.90 -     *                      converted, represented as a MethodType.
    1.91 -     * @param implMethod The implementation method which should be called
    1.92 -     *                   (with suitable adaptation of argument types, return
    1.93 -     *                   types, and adjustment for captured arguments) when
    1.94 -     *                   methods of the resulting functional interface instance
    1.95 -     *                   are invoked.
    1.96 -     * @param instantiatedMethodType The signature of the primary functional
    1.97 -     *                               interface method after type variables are
    1.98 -     *                               substituted with their instantiation from
    1.99 -     *                               the capture site
   1.100 -     * @param isSerializable Should the lambda be made serializable?  If set,
   1.101 -     *                       either the target type or one of the additional SAM
   1.102 -     *                       types must extend {@code Serializable}.
   1.103 -     * @param markerInterfaces Additional interfaces which the lambda object
   1.104 -     *                       should implement.
   1.105 -     * @param additionalBridges Method types for additional signatures to be
   1.106 -     *                          bridged to the implementation method
   1.107 -     * @throws LambdaConversionException If any of the meta-factory protocol
   1.108 -     * invariants are violated
   1.109 -     */
   1.110 -    AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller,
   1.111 -                                       MethodType invokedType,
   1.112 -                                       String samMethodName,
   1.113 -                                       MethodType samMethodType,
   1.114 -                                       MethodHandle implMethod,
   1.115 -                                       MethodType instantiatedMethodType,
   1.116 -                                       boolean isSerializable,
   1.117 -                                       Class<?>[] markerInterfaces,
   1.118 -                                       MethodType[] additionalBridges)
   1.119 -            throws LambdaConversionException {
   1.120 -        if ((caller.lookupModes() & MethodHandles.Lookup.PRIVATE) == 0) {
   1.121 -            throw new LambdaConversionException(String.format(
   1.122 -                    "Invalid caller: %s",
   1.123 -                    caller.lookupClass().getName()));
   1.124 -        }
   1.125 -        this.targetClass = caller.lookupClass();
   1.126 -        this.invokedType = invokedType;
   1.127 -
   1.128 -        this.samBase = invokedType.returnType();
   1.129 -
   1.130 -        this.samMethodName = samMethodName;
   1.131 -        this.samMethodType  = samMethodType;
   1.132 -
   1.133 -        this.implMethod = implMethod;
   1.134 -        this.implInfo = caller.revealDirect(implMethod);
   1.135 -        this.implKind = implInfo.getReferenceKind();
   1.136 -        this.implIsInstanceMethod =
   1.137 -                implKind == MethodHandleInfo.REF_invokeVirtual ||
   1.138 -                implKind == MethodHandleInfo.REF_invokeSpecial ||
   1.139 -                implKind == MethodHandleInfo.REF_invokeInterface;
   1.140 -        this.implDefiningClass = implInfo.getDeclaringClass();
   1.141 -        this.implMethodType = implInfo.getMethodType();
   1.142 -        this.instantiatedMethodType = instantiatedMethodType;
   1.143 -        this.isSerializable = isSerializable;
   1.144 -        this.markerInterfaces = markerInterfaces;
   1.145 -        this.additionalBridges = additionalBridges;
   1.146 -
   1.147 -        if (!samBase.isInterface()) {
   1.148 -            throw new LambdaConversionException(String.format(
   1.149 -                    "Functional interface %s is not an interface",
   1.150 -                    samBase.getName()));
   1.151 -        }
   1.152 -
   1.153 -        for (Class<?> c : markerInterfaces) {
   1.154 -            if (!c.isInterface()) {
   1.155 -                throw new LambdaConversionException(String.format(
   1.156 -                        "Marker interface %s is not an interface",
   1.157 -                        c.getName()));
   1.158 -            }
   1.159 -        }
   1.160 -    }
   1.161 -
   1.162 -    /**
   1.163 -     * Build the CallSite.
   1.164 -     *
   1.165 -     * @return a CallSite, which, when invoked, will return an instance of the
   1.166 -     * functional interface
   1.167 -     * @throws ReflectiveOperationException
   1.168 -     */
   1.169 -    abstract CallSite buildCallSite()
   1.170 -            throws LambdaConversionException;
   1.171 -
   1.172 -    /**
   1.173 -     * Check the meta-factory arguments for errors
   1.174 -     * @throws LambdaConversionException if there are improper conversions
   1.175 -     */
   1.176 -    void validateMetafactoryArgs() throws LambdaConversionException {
   1.177 -        switch (implKind) {
   1.178 -            case MethodHandleInfo.REF_invokeInterface:
   1.179 -            case MethodHandleInfo.REF_invokeVirtual:
   1.180 -            case MethodHandleInfo.REF_invokeStatic:
   1.181 -            case MethodHandleInfo.REF_newInvokeSpecial:
   1.182 -            case MethodHandleInfo.REF_invokeSpecial:
   1.183 -                break;
   1.184 -            default:
   1.185 -                throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
   1.186 -        }
   1.187 -
   1.188 -        // Check arity: optional-receiver + captured + SAM == impl
   1.189 -        final int implArity = implMethodType.parameterCount();
   1.190 -        final int receiverArity = implIsInstanceMethod ? 1 : 0;
   1.191 -        final int capturedArity = invokedType.parameterCount();
   1.192 -        final int samArity = samMethodType.parameterCount();
   1.193 -        final int instantiatedArity = instantiatedMethodType.parameterCount();
   1.194 -        if (implArity + receiverArity != capturedArity + samArity) {
   1.195 -            throw new LambdaConversionException(
   1.196 -                    String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
   1.197 -                                  implIsInstanceMethod ? "instance" : "static", implInfo,
   1.198 -                                  capturedArity, samArity, implArity));
   1.199 -        }
   1.200 -        if (instantiatedArity != samArity) {
   1.201 -            throw new LambdaConversionException(
   1.202 -                    String.format("Incorrect number of parameters for %s method %s; %d instantiated parameters, %d functional interface method parameters",
   1.203 -                                  implIsInstanceMethod ? "instance" : "static", implInfo,
   1.204 -                                  instantiatedArity, samArity));
   1.205 -        }
   1.206 -        for (MethodType bridgeMT : additionalBridges) {
   1.207 -            if (bridgeMT.parameterCount() != samArity) {
   1.208 -                throw new LambdaConversionException(
   1.209 -                        String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
   1.210 -                                      bridgeMT, samMethodType));
   1.211 -            }
   1.212 -        }
   1.213 -
   1.214 -        // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
   1.215 -        final int capturedStart;
   1.216 -        final int samStart;
   1.217 -        if (implIsInstanceMethod) {
   1.218 -            final Class<?> receiverClass;
   1.219 -
   1.220 -            // implementation is an instance method, adjust for receiver in captured variables / SAM arguments
   1.221 -            if (capturedArity == 0) {
   1.222 -                // receiver is function parameter
   1.223 -                capturedStart = 0;
   1.224 -                samStart = 1;
   1.225 -                receiverClass = instantiatedMethodType.parameterType(0);
   1.226 -            } else {
   1.227 -                // receiver is a captured variable
   1.228 -                capturedStart = 1;
   1.229 -                samStart = 0;
   1.230 -                receiverClass = invokedType.parameterType(0);
   1.231 -            }
   1.232 -
   1.233 -            // check receiver type
   1.234 -            if (!implDefiningClass.isAssignableFrom(receiverClass)) {
   1.235 -                throw new LambdaConversionException(
   1.236 -                        String.format("Invalid receiver type %s; not a subtype of implementation type %s",
   1.237 -                                      receiverClass, implDefiningClass));
   1.238 -            }
   1.239 -
   1.240 -           Class<?> implReceiverClass = implMethod.type().parameterType(0);
   1.241 -           if (implReceiverClass != implDefiningClass && !implReceiverClass.isAssignableFrom(receiverClass)) {
   1.242 -               throw new LambdaConversionException(
   1.243 -                       String.format("Invalid receiver type %s; not a subtype of implementation receiver type %s",
   1.244 -                                     receiverClass, implReceiverClass));
   1.245 -            }
   1.246 -        } else {
   1.247 -            // no receiver
   1.248 -            capturedStart = 0;
   1.249 -            samStart = 0;
   1.250 -        }
   1.251 -
   1.252 -        // Check for exact match on non-receiver captured arguments
   1.253 -        final int implFromCaptured = capturedArity - capturedStart;
   1.254 -        for (int i=0; i<implFromCaptured; i++) {
   1.255 -            Class<?> implParamType = implMethodType.parameterType(i);
   1.256 -            Class<?> capturedParamType = invokedType.parameterType(i + capturedStart);
   1.257 -            if (!capturedParamType.equals(implParamType)) {
   1.258 -                throw new LambdaConversionException(
   1.259 -                        String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
   1.260 -                                      i, capturedParamType, implParamType));
   1.261 -            }
   1.262 -        }
   1.263 -        // Check for adaptation match on SAM arguments
   1.264 -        final int samOffset = samStart - implFromCaptured;
   1.265 -        for (int i=implFromCaptured; i<implArity; i++) {
   1.266 -            Class<?> implParamType = implMethodType.parameterType(i);
   1.267 -            Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i + samOffset);
   1.268 -            if (!isAdaptableTo(instantiatedParamType, implParamType, true)) {
   1.269 -                throw new LambdaConversionException(
   1.270 -                        String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
   1.271 -                                      i, instantiatedParamType, implParamType));
   1.272 -            }
   1.273 -        }
   1.274 -
   1.275 -        // Adaptation match: return type
   1.276 -        Class<?> expectedType = instantiatedMethodType.returnType();
   1.277 -        Class<?> actualReturnType =
   1.278 -                (implKind == MethodHandleInfo.REF_newInvokeSpecial)
   1.279 -                  ? implDefiningClass
   1.280 -                  : implMethodType.returnType();
   1.281 -        Class<?> samReturnType = samMethodType.returnType();
   1.282 -        if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
   1.283 -            throw new LambdaConversionException(
   1.284 -                    String.format("Type mismatch for lambda return: %s is not convertible to %s",
   1.285 -                                  actualReturnType, expectedType));
   1.286 -        }
   1.287 -        if (!isAdaptableToAsReturnStrict(expectedType, samReturnType)) {
   1.288 -            throw new LambdaConversionException(
   1.289 -                    String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
   1.290 -                                  expectedType, samReturnType));
   1.291 -        }
   1.292 -        for (MethodType bridgeMT : additionalBridges) {
   1.293 -            if (!isAdaptableToAsReturnStrict(expectedType, bridgeMT.returnType())) {
   1.294 -                throw new LambdaConversionException(
   1.295 -                        String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
   1.296 -                                      expectedType, bridgeMT.returnType()));
   1.297 -            }
   1.298 -        }
   1.299 -     }
   1.300 -
   1.301 -    /**
   1.302 -     * Check type adaptability for parameter types.
   1.303 -     * @param fromType Type to convert from
   1.304 -     * @param toType Type to convert to
   1.305 -     * @param strict If true, do strict checks, else allow that fromType may be parameterized
   1.306 -     * @return True if 'fromType' can be passed to an argument of 'toType'
   1.307 -     */
   1.308 -    private boolean isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict) {
   1.309 -        if (fromType.equals(toType)) {
   1.310 -            return true;
   1.311 -        }
   1.312 -        if (fromType.isPrimitive()) {
   1.313 -            Wrapper wfrom = forPrimitiveType(fromType);
   1.314 -            if (toType.isPrimitive()) {
   1.315 -                // both are primitive: widening
   1.316 -                Wrapper wto = forPrimitiveType(toType);
   1.317 -                return wto.isConvertibleFrom(wfrom);
   1.318 -            } else {
   1.319 -                // from primitive to reference: boxing
   1.320 -                return toType.isAssignableFrom(wfrom.wrapperType());
   1.321 -            }
   1.322 -        } else {
   1.323 -            if (toType.isPrimitive()) {
   1.324 -                // from reference to primitive: unboxing
   1.325 -                Wrapper wfrom;
   1.326 -                if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) {
   1.327 -                    // fromType is a primitive wrapper; unbox+widen
   1.328 -                    Wrapper wto = forPrimitiveType(toType);
   1.329 -                    return wto.isConvertibleFrom(wfrom);
   1.330 -                } else {
   1.331 -                    // must be convertible to primitive
   1.332 -                    return !strict;
   1.333 -                }
   1.334 -            } else {
   1.335 -                // both are reference types: fromType should be a superclass of toType.
   1.336 -                return !strict || toType.isAssignableFrom(fromType);
   1.337 -            }
   1.338 -        }
   1.339 -    }
   1.340 -
   1.341 -    /**
   1.342 -     * Check type adaptability for return types --
   1.343 -     * special handling of void type) and parameterized fromType
   1.344 -     * @return True if 'fromType' can be converted to 'toType'
   1.345 -     */
   1.346 -    private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) {
   1.347 -        return toType.equals(void.class)
   1.348 -               || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
   1.349 -    }
   1.350 -    private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
   1.351 -        if (fromType.equals(void.class)) return toType.equals(void.class);
   1.352 -        return isAdaptableTo(fromType, toType, true);
   1.353 -    }
   1.354 -
   1.355 -
   1.356 -    /*********** Logging support -- for debugging only, uncomment as needed
   1.357 -    static final Executor logPool = Executors.newSingleThreadExecutor();
   1.358 -    protected static void log(final String s) {
   1.359 -        MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
   1.360 -            @Override
   1.361 -            public void run() {
   1.362 -                System.out.println(s);
   1.363 -            }
   1.364 -        });
   1.365 -    }
   1.366 -
   1.367 -    protected static void log(final String s, final Throwable e) {
   1.368 -        MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
   1.369 -            @Override
   1.370 -            public void run() {
   1.371 -                System.out.println(s);
   1.372 -                e.printStackTrace(System.out);
   1.373 -            }
   1.374 -        });
   1.375 -    }
   1.376 -    ***********************/
   1.377 -
   1.378 -}