1 /* 2 * Copyright (c) 2017, 2019, 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 26 package java.lang.runtime; 27 28 import java.lang.invoke.ConstantCallSite; 29 import java.lang.invoke.MethodHandle; 30 import java.lang.invoke.MethodHandles; 31 import java.lang.invoke.MethodType; 32 import java.lang.invoke.TypeDescriptor; 33 import java.security.AccessController; 34 import java.security.PrivilegedAction; 35 import java.util.Arrays; 36 import java.util.HashMap; 37 import java.util.List; 38 import java.util.Objects; 39 40 /** 41 * {@preview Associated with records, a preview feature of the Java language. 42 * 43 * This class is associated with <i>records</i>, a preview 44 * feature of the Java language. Preview features 45 * may be removed in a future release, or upgraded to permanent 46 * features of the Java language.} 47 * 48 * Bootstrap methods for state-driven implementations of core methods, 49 * including {@link Object#equals(Object)}, {@link Object#hashCode()}, and 50 * {@link Object#toString()}. These methods may be used, for example, by 51 * Java™ compiler implementations to implement the bodies of {@link Object} 52 * methods for record classes. 53 * 54 * @since 14 55 */ 56 @jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS, 57 essentialAPI=false) 58 public class ObjectMethods { 59 60 private ObjectMethods() { } 61 62 private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class); 63 private static final MethodType NAMES_MT = MethodType.methodType(List.class); 64 private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false); 65 private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true); 66 private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0); 67 private static final MethodHandle CLASS_IS_INSTANCE; 68 private static final MethodHandle OBJECT_EQUALS; 69 private static final MethodHandle OBJECTS_EQUALS; 70 private static final MethodHandle OBJECTS_HASHCODE; 71 private static final MethodHandle OBJECTS_TOSTRING; 72 private static final MethodHandle OBJECT_EQ; 73 private static final MethodHandle OBJECT_HASHCODE; 74 private static final MethodHandle OBJECT_TO_STRING; 75 private static final MethodHandle STRING_FORMAT; 76 private static final MethodHandle HASH_COMBINER; 77 78 private static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>(); 79 private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>(); 80 private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>(); 81 82 static { 83 try { 84 @SuppressWarnings("preview") 85 Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class; 86 MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); 87 MethodHandles.Lookup lookup = MethodHandles.lookup(); 88 89 ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { 90 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); } 91 }); 92 93 CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance", 94 MethodType.methodType(boolean.class, Object.class)); 95 OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals", 96 MethodType.methodType(boolean.class, Object.class)); 97 OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode", 98 MethodType.fromMethodDescriptorString("()I", loader)); 99 OBJECT_TO_STRING = publicLookup.findVirtual(Object.class, "toString", 100 MethodType.methodType(String.class)); 101 STRING_FORMAT = publicLookup.findStatic(String.class, "format", 102 MethodType.methodType(String.class, String.class, Object[].class)); 103 OBJECTS_EQUALS = publicLookup.findStatic(Objects.class, "equals", 104 MethodType.methodType(boolean.class, Object.class, Object.class)); 105 OBJECTS_HASHCODE = publicLookup.findStatic(Objects.class, "hashCode", 106 MethodType.methodType(int.class, Object.class)); 107 OBJECTS_TOSTRING = publicLookup.findStatic(Objects.class, "toString", 108 MethodType.methodType(String.class, Object.class)); 109 110 OBJECT_EQ = lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 111 MethodType.methodType(boolean.class, Object.class, Object.class)); 112 HASH_COMBINER = lookup.findStatic(OBJECT_METHODS_CLASS, "hashCombiner", 113 MethodType.fromMethodDescriptorString("(II)I", loader)); 114 115 primitiveEquals.put(byte.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 116 MethodType.fromMethodDescriptorString("(BB)Z", loader))); 117 primitiveEquals.put(short.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 118 MethodType.fromMethodDescriptorString("(SS)Z", loader))); 119 primitiveEquals.put(char.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 120 MethodType.fromMethodDescriptorString("(CC)Z", loader))); 121 primitiveEquals.put(int.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 122 MethodType.fromMethodDescriptorString("(II)Z", loader))); 123 primitiveEquals.put(long.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 124 MethodType.fromMethodDescriptorString("(JJ)Z", loader))); 125 primitiveEquals.put(float.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 126 MethodType.fromMethodDescriptorString("(FF)Z", loader))); 127 primitiveEquals.put(double.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 128 MethodType.fromMethodDescriptorString("(DD)Z", loader))); 129 primitiveEquals.put(boolean.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 130 MethodType.fromMethodDescriptorString("(ZZ)Z", loader))); 131 132 primitiveHashers.put(byte.class, lookup.findStatic(Byte.class, "hashCode", 133 MethodType.fromMethodDescriptorString("(B)I", loader))); 134 primitiveHashers.put(short.class, lookup.findStatic(Short.class, "hashCode", 135 MethodType.fromMethodDescriptorString("(S)I", loader))); 136 primitiveHashers.put(char.class, lookup.findStatic(Character.class, "hashCode", 137 MethodType.fromMethodDescriptorString("(C)I", loader))); 138 primitiveHashers.put(int.class, lookup.findStatic(Integer.class, "hashCode", 139 MethodType.fromMethodDescriptorString("(I)I", loader))); 140 primitiveHashers.put(long.class, lookup.findStatic(Long.class, "hashCode", 141 MethodType.fromMethodDescriptorString("(J)I", loader))); 142 primitiveHashers.put(float.class, lookup.findStatic(Float.class, "hashCode", 143 MethodType.fromMethodDescriptorString("(F)I", loader))); 144 primitiveHashers.put(double.class, lookup.findStatic(Double.class, "hashCode", 145 MethodType.fromMethodDescriptorString("(D)I", loader))); 146 primitiveHashers.put(boolean.class, lookup.findStatic(Boolean.class, "hashCode", 147 MethodType.fromMethodDescriptorString("(Z)I", loader))); 148 149 primitiveToString.put(byte.class, lookup.findStatic(Byte.class, "toString", 150 MethodType.methodType(String.class, byte.class))); 151 primitiveToString.put(short.class, lookup.findStatic(Short.class, "toString", 152 MethodType.methodType(String.class, short.class))); 153 primitiveToString.put(char.class, lookup.findStatic(Character.class, "toString", 154 MethodType.methodType(String.class, char.class))); 155 primitiveToString.put(int.class, lookup.findStatic(Integer.class, "toString", 156 MethodType.methodType(String.class, int.class))); 157 primitiveToString.put(long.class, lookup.findStatic(Long.class, "toString", 158 MethodType.methodType(String.class, long.class))); 159 primitiveToString.put(float.class, lookup.findStatic(Float.class, "toString", 160 MethodType.methodType(String.class, float.class))); 161 primitiveToString.put(double.class, lookup.findStatic(Double.class, "toString", 162 MethodType.methodType(String.class, double.class))); 163 primitiveToString.put(boolean.class, lookup.findStatic(Boolean.class, "toString", 164 MethodType.methodType(String.class, boolean.class))); 165 } 166 catch (ReflectiveOperationException e) { 167 throw new RuntimeException(e); 168 } 169 } 170 171 private static int hashCombiner(int x, int y) { 172 return x*31 + y; 173 } 174 175 private static boolean eq(Object a, Object b) { return a == b; } 176 private static boolean eq(byte a, byte b) { return a == b; } 177 private static boolean eq(short a, short b) { return a == b; } 178 private static boolean eq(char a, char b) { return a == b; } 179 private static boolean eq(int a, int b) { return a == b; } 180 private static boolean eq(long a, long b) { return a == b; } 181 private static boolean eq(float a, float b) { return Float.compare(a, b) == 0; } 182 private static boolean eq(double a, double b) { return Double.compare(a, b) == 0; } 183 private static boolean eq(boolean a, boolean b) { return a == b; } 184 185 /** Get the method handle for combining two values of a given type */ 186 private static MethodHandle equalator(Class<?> clazz) { 187 return (clazz.isPrimitive() 188 ? primitiveEquals.get(clazz) 189 : OBJECTS_EQUALS.asType(MethodType.methodType(boolean.class, clazz, clazz))); 190 } 191 192 /** Get the hasher for a value of a given type */ 193 private static MethodHandle hasher(Class<?> clazz) { 194 return (clazz.isPrimitive() 195 ? primitiveHashers.get(clazz) 196 : OBJECTS_HASHCODE.asType(MethodType.methodType(int.class, clazz))); 197 } 198 199 /** Get the stringifier for a value of a given type */ 200 private static MethodHandle stringifier(Class<?> clazz) { 201 return (clazz.isPrimitive() 202 ? primitiveToString.get(clazz) 203 : OBJECTS_TOSTRING.asType(MethodType.methodType(String.class, clazz))); 204 } 205 206 /** 207 * Generates a method handle for the {@code equals} method for a given data class 208 * @param receiverClass the data class 209 * @param getters the list of getters 210 * @return the method handle 211 */ 212 private static MethodHandle makeEquals(Class<?> receiverClass, 213 List<MethodHandle> getters) { 214 MethodType rr = MethodType.methodType(boolean.class, receiverClass, receiverClass); 215 MethodType ro = MethodType.methodType(boolean.class, receiverClass, Object.class); 216 MethodHandle instanceFalse = MethodHandles.dropArguments(FALSE, 0, receiverClass, Object.class); // (RO)Z 217 MethodHandle instanceTrue = MethodHandles.dropArguments(TRUE, 0, receiverClass, Object.class); // (RO)Z 218 MethodHandle isSameObject = OBJECT_EQ.asType(ro); // (RO)Z 219 MethodHandle isInstance = MethodHandles.dropArguments(CLASS_IS_INSTANCE.bindTo(receiverClass), 0, receiverClass); // (RO)Z 220 MethodHandle accumulator = MethodHandles.dropArguments(TRUE, 0, receiverClass, receiverClass); // (RR)Z 221 222 for (MethodHandle getter : getters) { 223 MethodHandle equalator = equalator(getter.type().returnType()); // (TT)Z 224 MethodHandle thisFieldEqual = MethodHandles.filterArguments(equalator, 0, getter, getter); // (RR)Z 225 accumulator = MethodHandles.guardWithTest(thisFieldEqual, accumulator, instanceFalse.asType(rr)); 226 } 227 228 return MethodHandles.guardWithTest(isSameObject, 229 instanceTrue, 230 MethodHandles.guardWithTest(isInstance, accumulator.asType(ro), instanceFalse)); 231 } 232 233 /** 234 * Generates a method handle for the {@code hashCode} method for a given data class 235 * @param receiverClass the data class 236 * @param getters the list of getters 237 * @return the method handle 238 */ 239 private static MethodHandle makeHashCode(Class<?> receiverClass, 240 List<MethodHandle> getters) { 241 MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I 242 243 // @@@ Use loop combinator instead? 244 for (MethodHandle getter : getters) { 245 MethodHandle hasher = hasher(getter.type().returnType()); // (T)I 246 MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter); // (R)I 247 MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I 248 accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I 249 } 250 251 return accumulator; 252 } 253 254 /** 255 * Generates a method handle for the {@code toString} method for a given data class 256 * @param receiverClass the data class 257 * @param getters the list of getters 258 * @param names the names 259 * @return the method handle 260 */ 261 private static MethodHandle makeToString(Class<?> receiverClass, 262 List<MethodHandle> getters, 263 List<String> names) { 264 // This is a pretty lousy algorithm; we spread the receiver over N places, 265 // apply the N getters, apply N toString operations, and concat the result with String.format 266 // Better to use String.format directly, or delegate to StringConcatFactory 267 // Also probably want some quoting around String components 268 269 assert getters.size() == names.size(); 270 271 int[] invArgs = new int[getters.size()]; 272 Arrays.fill(invArgs, 0); 273 MethodHandle[] filters = new MethodHandle[getters.size()]; 274 StringBuilder sb = new StringBuilder(); 275 sb.append(receiverClass.getSimpleName()).append("["); 276 for (int i=0; i<getters.size(); i++) { 277 MethodHandle getter = getters.get(i); // (R)T 278 MethodHandle stringify = stringifier(getter.type().returnType()); // (T)String 279 MethodHandle stringifyThisField = MethodHandles.filterArguments(stringify, 0, getter); // (R)String 280 filters[i] = stringifyThisField; 281 sb.append(names.get(i)).append("=%s"); 282 if (i != getters.size() - 1) 283 sb.append(", "); 284 } 285 sb.append(']'); 286 String formatString = sb.toString(); 287 MethodHandle formatter = MethodHandles.insertArguments(STRING_FORMAT, 0, formatString) 288 .asCollector(String[].class, getters.size()); // (R*)String 289 if (getters.size() == 0) { 290 // Add back extra R 291 formatter = MethodHandles.dropArguments(formatter, 0, receiverClass); 292 } 293 else { 294 MethodHandle filtered = MethodHandles.filterArguments(formatter, 0, filters); 295 formatter = MethodHandles.permuteArguments(filtered, MethodType.methodType(String.class, receiverClass), invArgs); 296 } 297 298 return formatter; 299 } 300 301 /** 302 * Bootstrap method to generate the {@link Object#equals(Object)}, 303 * {@link Object#hashCode()}, and {@link Object#toString()} methods, based 304 * on a description of the component names and accessor methods, for either 305 * {@code invokedynamic} call sites or dynamic constant pool entries. 306 * 307 * For more detail on the semantics of the generated methods see the specification 308 * of {@link java.lang.Record#equals(Object)}, {@link java.lang.Record#hashCode()} and 309 * {@link java.lang.Record#toString()}. 310 * 311 * 312 * @param lookup Every bootstrap method is expected to have a {@code lookup} 313 * which usually represents a lookup context with the 314 * accessibility privileges of the caller. This is because 315 * {@code invokedynamic} call sites always provide a {@code lookup} 316 * to the corresponding bootstrap method, but this method just 317 * ignores the {@code lookup} parameter 318 * @param methodName the name of the method to generate, which must be one of 319 * {@code "equals"}, {@code "hashCode"}, or {@code "toString"} 320 * @param type a {@link MethodType} corresponding the descriptor type 321 * for the method, which must correspond to the descriptor 322 * for the corresponding {@link Object} method, if linking 323 * an {@code invokedynamic} call site, or the 324 * constant {@code MethodHandle.class}, if linking a 325 * dynamic constant 326 * @param recordClass the record class hosting the record components 327 * @param names the list of component names, joined into a string 328 * separated by ";", or the empty string if there are no 329 * components. Maybe be null, if the {@code methodName} 330 * is {@code "equals"} or {@code "hashCode"}. 331 * @param getters method handles for the accessor methods for the components 332 * @return a call site if invoked by indy, or a method handle 333 * if invoked by a condy 334 * @throws IllegalArgumentException if the bootstrap arguments are invalid 335 * or inconsistent 336 * @throws Throwable if any exception is thrown during call site construction 337 */ 338 public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type, 339 Class<?> recordClass, 340 String names, 341 MethodHandle... getters) throws Throwable { 342 MethodType methodType; 343 if (type instanceof MethodType) 344 methodType = (MethodType) type; 345 else { 346 methodType = null; 347 if (!MethodHandle.class.equals(type)) 348 throw new IllegalArgumentException(type.toString()); 349 } 350 List<MethodHandle> getterList = List.of(getters); 351 MethodHandle handle; 352 switch (methodName) { 353 case "equals": 354 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, recordClass, Object.class))) 355 throw new IllegalArgumentException("Bad method type: " + methodType); 356 handle = makeEquals(recordClass, getterList); 357 return methodType != null ? new ConstantCallSite(handle) : handle; 358 case "hashCode": 359 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, recordClass))) 360 throw new IllegalArgumentException("Bad method type: " + methodType); 361 handle = makeHashCode(recordClass, getterList); 362 return methodType != null ? new ConstantCallSite(handle) : handle; 363 case "toString": 364 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, recordClass))) 365 throw new IllegalArgumentException("Bad method type: " + methodType); 366 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";")); 367 if (nameList.size() != getterList.size()) 368 throw new IllegalArgumentException("Name list and accessor list do not match"); 369 handle = makeToString(recordClass, getterList, nameList); 370 return methodType != null ? new ConstantCallSite(handle) : handle; 371 default: 372 throw new IllegalArgumentException(methodName); 373 } 374 } 375 }