1 /* 2 * Copyright (c) 2012, 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 package java.lang.invoke; 26 27 import sun.invoke.util.Wrapper; 28 29 import static sun.invoke.util.Wrapper.forPrimitiveType; 30 import static sun.invoke.util.Wrapper.forWrapperType; 31 import static sun.invoke.util.Wrapper.isWrapperType; 32 33 /** 34 * Abstract implementation of a lambda metafactory which provides parameter unrolling and input validation. 35 * 36 * @see LambdaMetafactory 37 */ 38 /* package */ abstract class AbstractValidatingLambdaMetafactory { 39 40 /* 41 * For context, the comments for the following fields are marked in quotes with their values, given this program: 42 * interface II<T> { Object foo(T x); } 43 * interface JJ<R extends Number> extends II<R> { } 44 * class CC { String impl(int i) { return "impl:"+i; }} 45 * class X { 46 * public static void main(String[] args) { 47 * JJ<Integer> iii = (new CC())::impl; 48 * System.out.printf(">>> %s\n", iii.foo(44)); 49 * }} 50 */ 51 final Class<?> targetClass; // The class calling the meta-factory via invokedynamic "class X" 52 final MethodType invokedType; // The type of the invoked method "(CC)II" 53 final Class<?> samBase; // The type of the returned instance "interface JJ" 54 final MethodHandle samMethod; // Raw method handle for the functional interface method 55 final MethodHandleInfo samInfo; // Info about the SAM method handle "MethodHandleInfo[9 II.foo(Object)Object]" 56 final Class<?> samClass; // Interface containing the SAM method "interface II" 57 final MethodType samMethodType; // Type of the SAM method "(Object)Object" 58 final MethodHandle implMethod; // Raw method handle for the implementation method 59 final MethodHandleInfo implInfo; // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]" 60 final int implKind; // Invocation kind for implementation "5"=invokevirtual 61 final boolean implIsInstanceMethod; // Is the implementation an instance method "true" 62 final Class<?> implDefiningClass; // Type defining the implementation "class CC" 63 final MethodType implMethodType; // Type of the implementation method "(int)String" 64 final MethodType instantiatedMethodType; // Instantiated erased functional interface method type "(Integer)Object" 65 final boolean isSerializable; // Should the returned instance be serializable 66 final Class<?>[] markerInterfaces; // Additional marker interfaces to be implemented 67 final MethodType[] additionalBridges; // Signatures of additional methods to bridge 68 69 70 /** 71 * Meta-factory constructor. 72 * 73 * @param caller Stacked automatically by VM; represents a lookup context 74 * with the accessibility privileges of the caller. 75 * @param invokedType Stacked automatically by VM; the signature of the 76 * invoked method, which includes the expected static 77 * type of the returned lambda object, and the static 78 * types of the captured arguments for the lambda. In 79 * the event that the implementation method is an 80 * instance method, the first argument in the invocation 81 * signature will correspond to the receiver. 82 * @param samMethod The primary method in the functional interface to which 83 * the lambda or method reference is being converted, 84 * represented as a method handle. 85 * @param implMethod The implementation method which should be called 86 * (with suitable adaptation of argument types, return 87 * types, and adjustment for captured arguments) when 88 * methods of the resulting functional interface instance 89 * are invoked. 90 * @param instantiatedMethodType The signature of the primary functional 91 * interface method after type variables are 92 * substituted with their instantiation from 93 * the capture site 94 * @param isSerializable Should the lambda be made serializable? If set, 95 * either the target type or one of the additional SAM 96 * types must extend {@code Serializable}. 97 * @param markerInterfaces Additional interfaces which the lambda object 98 * should implement. 99 * @param additionalBridges Method types for additional signatures to be 100 * bridged to the implementation method 101 * @throws ReflectiveOperationException 102 * @throws LambdaConversionException If any of the meta-factory protocol 103 * invariants are violated 104 */ 105 AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller, 106 MethodType invokedType, 107 MethodHandle samMethod, 108 MethodHandle implMethod, 109 MethodType instantiatedMethodType, 110 boolean isSerializable, 111 Class<?>[] markerInterfaces, 112 MethodType[] additionalBridges) 113 throws ReflectiveOperationException, LambdaConversionException { 114 this.targetClass = caller.lookupClass(); 115 this.invokedType = invokedType; 116 117 this.samBase = invokedType.returnType(); 118 119 this.samMethod = samMethod; 120 this.samInfo = new MethodHandleInfo(samMethod); 121 this.samClass = samInfo.getDeclaringClass(); 122 this.samMethodType = samInfo.getMethodType(); 123 124 this.implMethod = implMethod; 125 this.implInfo = new MethodHandleInfo(implMethod); 126 // @@@ Temporary work-around pending resolution of 8005119 127 this.implKind = (implInfo.getReferenceKind() == MethodHandleInfo.REF_invokeSpecial) 128 ? MethodHandleInfo.REF_invokeVirtual 129 : implInfo.getReferenceKind(); 130 this.implIsInstanceMethod = 131 implKind == MethodHandleInfo.REF_invokeVirtual || 132 implKind == MethodHandleInfo.REF_invokeSpecial || 133 implKind == MethodHandleInfo.REF_invokeInterface; 134 this.implDefiningClass = implInfo.getDeclaringClass(); 135 this.implMethodType = implInfo.getMethodType(); 136 this.instantiatedMethodType = instantiatedMethodType; 137 this.isSerializable = isSerializable; 138 this.markerInterfaces = markerInterfaces; 139 this.additionalBridges = additionalBridges; 140 141 if (!samClass.isInterface()) { 142 throw new LambdaConversionException(String.format( 143 "Functional interface %s is not an interface", samClass.getName())); 144 } 145 146 for (Class<?> c : markerInterfaces) { 147 if (!c.isInterface()) { 148 throw new LambdaConversionException(String.format( 149 "Marker interface %s is not an interface", c.getName())); 150 } 151 } 152 } 153 154 /** 155 * Build the CallSite. 156 * 157 * @return a CallSite, which, when invoked, will return an instance of the 158 * functional interface 159 * @throws ReflectiveOperationException 160 */ 161 abstract CallSite buildCallSite() throws ReflectiveOperationException, LambdaConversionException; 162 163 /** 164 * Check the meta-factory arguments for errors 165 * @throws LambdaConversionException if there are improper conversions 166 */ 167 void validateMetafactoryArgs() throws LambdaConversionException { 168 // Check target type is a subtype of class where SAM method is defined 169 if (!samClass.isAssignableFrom(samBase)) { 170 throw new LambdaConversionException( 171 String.format("Invalid target type %s for lambda conversion; not a subtype of functional interface %s", 172 samBase.getName(), samClass.getName())); 173 } 174 175 switch (implKind) { 176 case MethodHandleInfo.REF_invokeInterface: 177 case MethodHandleInfo.REF_invokeVirtual: 178 case MethodHandleInfo.REF_invokeStatic: 179 case MethodHandleInfo.REF_newInvokeSpecial: 180 case MethodHandleInfo.REF_invokeSpecial: 181 break; 182 default: 183 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo)); 184 } 185 186 // Check arity: optional-receiver + captured + SAM == impl 187 final int implArity = implMethodType.parameterCount(); 188 final int receiverArity = implIsInstanceMethod ? 1 : 0; 189 final int capturedArity = invokedType.parameterCount(); 190 final int samArity = samMethodType.parameterCount(); 191 final int instantiatedArity = instantiatedMethodType.parameterCount(); 192 if (implArity + receiverArity != capturedArity + samArity) { 193 throw new LambdaConversionException( 194 String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters", 195 implIsInstanceMethod ? "instance" : "static", implInfo, 196 capturedArity, samArity, implArity)); 197 } 198 if (instantiatedArity != samArity) { 199 throw new LambdaConversionException( 200 String.format("Incorrect number of parameters for %s method %s; %d instantiated parameters, %d functional interface method parameters", 201 implIsInstanceMethod ? "instance" : "static", implInfo, 202 instantiatedArity, samArity)); 203 } 204 205 // If instance: first captured arg (receiver) must be subtype of class where impl method is defined 206 final int capturedStart; 207 final int samStart; 208 if (implIsInstanceMethod) { 209 final Class<?> receiverClass; 210 211 // implementation is an instance method, adjust for receiver in captured variables / SAM arguments 212 if (capturedArity == 0) { 213 // receiver is function parameter 214 capturedStart = 0; 215 samStart = 1; 216 receiverClass = instantiatedMethodType.parameterType(0); 217 } else { 218 // receiver is a captured variable 219 capturedStart = 1; 220 samStart = 0; 221 receiverClass = invokedType.parameterType(0); 222 } 223 224 // check receiver type 225 if (!implDefiningClass.isAssignableFrom(receiverClass)) { 226 throw new LambdaConversionException( 227 String.format("Invalid receiver type %s; not a subtype of implementation type %s", 228 receiverClass, implDefiningClass)); 229 } 230 } else { 231 // no receiver 232 capturedStart = 0; 233 samStart = 0; 234 } 235 236 // Check for exact match on non-receiver captured arguments 237 final int implFromCaptured = capturedArity - capturedStart; 238 for (int i=0; i<implFromCaptured; i++) { 239 Class<?> implParamType = implMethodType.parameterType(i); 240 Class<?> capturedParamType = invokedType.parameterType(i + capturedStart); 241 if (!capturedParamType.equals(implParamType)) { 242 throw new LambdaConversionException( 243 String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s", 244 i, capturedParamType, implParamType)); 245 } 246 } 247 // Check for adaptation match on SAM arguments 248 final int samOffset = samStart - implFromCaptured; 249 for (int i=implFromCaptured; i<implArity; i++) { 250 Class<?> implParamType = implMethodType.parameterType(i); 251 Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i + samOffset); 252 if (!isAdaptableTo(instantiatedParamType, implParamType, true)) { 253 throw new LambdaConversionException( 254 String.format("Type mismatch for lambda argument %d: %s is not convertible to %s", 255 i, instantiatedParamType, implParamType)); 256 } 257 } 258 259 // Adaptation match: return type 260 Class<?> expectedType = instantiatedMethodType.returnType(); 261 Class<?> actualReturnType = 262 (implKind == MethodHandleInfo.REF_newInvokeSpecial) 263 ? implDefiningClass 264 : implMethodType.returnType(); 265 if (!isAdaptableToAsReturn(actualReturnType, expectedType)) { 266 throw new LambdaConversionException( 267 String.format("Type mismatch for lambda return: %s is not convertible to %s", 268 actualReturnType, expectedType)); 269 } 270 } 271 272 /** 273 * Check type adaptability for parameter types. 274 * @param fromType Type to convert from 275 * @param toType Type to convert to 276 * @param strict If true, do strict checks, else allow that fromType may be parameterized 277 * @return True if 'fromType' can be passed to an argument of 'toType' 278 */ 279 private boolean isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict) { 280 if (fromType.equals(toType)) { 281 return true; 282 } 283 if (fromType.isPrimitive()) { 284 Wrapper wfrom = forPrimitiveType(fromType); 285 if (toType.isPrimitive()) { 286 // both are primitive: widening 287 Wrapper wto = forPrimitiveType(toType); 288 return wto.isConvertibleFrom(wfrom); 289 } else { 290 // from primitive to reference: boxing 291 return toType.isAssignableFrom(wfrom.wrapperType()); 292 } 293 } else { 294 if (toType.isPrimitive()) { 295 // from reference to primitive: unboxing 296 Wrapper wfrom; 297 if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) { 298 // fromType is a primitive wrapper; unbox+widen 299 Wrapper wto = forPrimitiveType(toType); 300 return wto.isConvertibleFrom(wfrom); 301 } else { 302 // must be convertible to primitive 303 return !strict; 304 } 305 } else { 306 // both are reference types: fromType should be a superclass of toType. 307 return !strict || toType.isAssignableFrom(fromType); 308 } 309 } 310 } 311 312 /** 313 * Check type adaptability for return types -- special handling of void type) 314 * and parameterized fromType 315 * @return True if 'fromType' can be converted to 'toType' 316 */ 317 private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) { 318 return toType.equals(void.class) 319 || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false); 320 } 321 322 323 /*********** Logging support -- for debugging only, uncomment as needed 324 static final Executor logPool = Executors.newSingleThreadExecutor(); 325 protected static void log(final String s) { 326 MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() { 327 @Override 328 public void run() { 329 System.out.println(s); 330 } 331 }); 332 } 333 334 protected static void log(final String s, final Throwable e) { 335 MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() { 336 @Override 337 public void run() { 338 System.out.println(s); 339 e.printStackTrace(System.out); 340 } 341 }); 342 } 343 ***********************/ 344 345 }