< prev index next >

src/java.base/share/classes/java/lang/runtime/ObjectMethods.java

Print this page

 55     private ObjectMethods() { }
 56 
 57     private static final int MAX_STRING_CONCAT_SLOTS = 20;
 58 
 59     private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
 60     private static final MethodType NAMES_MT = MethodType.methodType(List.class);
 61     private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
 62     private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true);
 63     private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0);
 64     private static final MethodHandle CLASS_IS_INSTANCE;
 65     private static final MethodHandle OBJECT_EQUALS;
 66     private static final MethodHandle OBJECTS_EQUALS;
 67     private static final MethodHandle OBJECTS_HASHCODE;
 68     private static final MethodHandle OBJECTS_TOSTRING;
 69     private static final MethodHandle OBJECT_EQ;
 70     private static final MethodHandle OBJECT_HASHCODE;
 71     private static final MethodHandle OBJECT_TO_STRING;
 72     private static final MethodHandle STRING_FORMAT;
 73     private static final MethodHandle HASH_COMBINER;
 74 
 75     private static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>();


 76     private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>();
 77     private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>();
 78 
 79     static {
 80         try {
 81             Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class;
 82             MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
 83             MethodHandles.Lookup lookup = MethodHandles.lookup();
 84 
 85             @SuppressWarnings("removal")
 86             ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
 87                 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); }
 88             });
 89 
 90             CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance",
 91                                                          MethodType.methodType(boolean.class, Object.class));
 92             OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals",
 93                                                      MethodType.methodType(boolean.class, Object.class));
 94             OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode",
 95                                                        MethodType.fromMethodDescriptorString("()I", loader));

234      * @return the method handle
235      */
236     private static MethodHandle makeHashCode(Class<?> receiverClass,
237                                             List<MethodHandle> getters) {
238         MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I
239 
240         // @@@ Use loop combinator instead?
241         for (MethodHandle getter : getters) {
242             MethodHandle hasher = hasher(getter.type().returnType()); // (T)I
243             MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter);    // (R)I
244             MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I
245             accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I
246         }
247 
248         return accumulator;
249     }
250 
251     /**
252      * Generates a method handle for the {@code toString} method for a given data class
253      * @param receiverClass   the data class

254      * @param getters         the list of getters
255      * @param names           the names
256      * @return the method handle
257      */
258     private static MethodHandle makeToString(MethodHandles.Lookup lookup,
259                                             Class<?> receiverClass,

260                                             MethodHandle[] getters,
261                                             List<String> names) {
262         assert getters.length == names.size();
263         if (getters.length == 0) {
264             // special case
265             MethodHandle emptyRecordCase = MethodHandles.constant(String.class, receiverClass.getSimpleName() + "[]");
266             emptyRecordCase = MethodHandles.dropArguments(emptyRecordCase, 0, receiverClass); // (R)S
267             return emptyRecordCase;
268         }
269 
270         boolean firstTime = true;
271         MethodHandle[] mhs;
272         List<List<MethodHandle>> splits;
273         MethodHandle[] toSplit = getters;
274         int namesIndex = 0;
275         do {
276             /* StringConcatFactory::makeConcatWithConstants can only deal with 200 slots, longs and double occupy two
277              * the rest 1 slot, we need to chop the current `getters` into chunks, it could be that for records with
278              * a lot of components that we need to do a couple of iterations. The main difference between the first
279              * iteration and the rest would be on the recipe
280              */
281             splits = split(toSplit);
282             mhs = new MethodHandle[splits.size()];
283             for (int splitIndex = 0; splitIndex < splits.size(); splitIndex++) {
284                 String recipe = "";
285                 if (firstTime && splitIndex == 0) {
286                     recipe = receiverClass.getSimpleName() + "[";
287                 }
288                 for (int i = 0; i < splits.get(splitIndex).size(); i++) {
289                     recipe += firstTime ? names.get(namesIndex) + "=" + "\1" : "\1";
290                     if (firstTime && namesIndex != names.size() - 1) {
291                         recipe += ", ";
292                     }
293                     namesIndex++;
294                 }
295                 if (firstTime && splitIndex == splits.size() - 1) {
296                     recipe += "]";
297                 }
298                 Class<?>[] concatTypeArgs = new Class<?>[splits.get(splitIndex).size()];
299                 // special case: no need to create another getters if there is only one split
300                 MethodHandle[] currentSplitGetters = new MethodHandle[splits.get(splitIndex).size()];
301                 for (int j = 0; j < splits.get(splitIndex).size(); j++) {
302                     concatTypeArgs[j] = splits.get(splitIndex).get(j).type().returnType();
303                     currentSplitGetters[j] = splits.get(splitIndex).get(j);
304                 }
305                 MethodType concatMT = MethodType.methodType(String.class, concatTypeArgs);
306                 try {

395      * @return             a call site if invoked by indy, or a method handle
396      *                     if invoked by a condy
397      * @throws IllegalArgumentException if the bootstrap arguments are invalid
398      *                                  or inconsistent
399      * @throws NullPointerException if any argument is {@code null} or if any element
400      *                              in the {@code getters} array is {@code null}
401      * @throws Throwable if any exception is thrown during call site construction
402      */
403     public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
404                                    Class<?> recordClass,
405                                    String names,
406                                    MethodHandle... getters) throws Throwable {
407         requireNonNull(lookup);
408         requireNonNull(methodName);
409         requireNonNull(type);
410         requireNonNull(recordClass);
411         requireNonNull(names);
412         requireNonNull(getters);
413         Arrays.stream(getters).forEach(Objects::requireNonNull);
414         MethodType methodType;
415         if (type instanceof MethodType mt)

416             methodType = mt;
417         else {



418             methodType = null;
419             if (!MethodHandle.class.equals(type))
420                 throw new IllegalArgumentException(type.toString());
421         }
422         List<MethodHandle> getterList = List.of(getters);





423         MethodHandle handle = switch (methodName) {
424             case "equals"   -> {
425                 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, recordClass, Object.class)))
426                     throw new IllegalArgumentException("Bad method type: " + methodType);
427                 yield makeEquals(recordClass, getterList);
428             }
429             case "hashCode" -> {
430                 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, recordClass)))
431                     throw new IllegalArgumentException("Bad method type: " + methodType);
432                 yield makeHashCode(recordClass, getterList);
433             }
434             case "toString" -> {
435                 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, recordClass)))
436                     throw new IllegalArgumentException("Bad method type: " + methodType);
437                 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
438                 if (nameList.size() != getterList.size())
439                     throw new IllegalArgumentException("Name list and accessor list do not match");
440                 yield makeToString(lookup, recordClass, getters, nameList);
441             }
442             default -> throw new IllegalArgumentException(methodName);
443         };
444         return methodType != null ? new ConstantCallSite(handle) : handle;
445     }
446 }

 55     private ObjectMethods() { }
 56 
 57     private static final int MAX_STRING_CONCAT_SLOTS = 20;
 58 
 59     private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
 60     private static final MethodType NAMES_MT = MethodType.methodType(List.class);
 61     private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
 62     private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true);
 63     private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0);
 64     private static final MethodHandle CLASS_IS_INSTANCE;
 65     private static final MethodHandle OBJECT_EQUALS;
 66     private static final MethodHandle OBJECTS_EQUALS;
 67     private static final MethodHandle OBJECTS_HASHCODE;
 68     private static final MethodHandle OBJECTS_TOSTRING;
 69     private static final MethodHandle OBJECT_EQ;
 70     private static final MethodHandle OBJECT_HASHCODE;
 71     private static final MethodHandle OBJECT_TO_STRING;
 72     private static final MethodHandle STRING_FORMAT;
 73     private static final MethodHandle HASH_COMBINER;
 74 
 75     /* package-private */
 76     static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>();
 77 
 78     private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>();
 79     private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>();
 80 
 81     static {
 82         try {
 83             Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class;
 84             MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
 85             MethodHandles.Lookup lookup = MethodHandles.lookup();
 86 
 87             @SuppressWarnings("removal")
 88             ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
 89                 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); }
 90             });
 91 
 92             CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance",
 93                                                          MethodType.methodType(boolean.class, Object.class));
 94             OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals",
 95                                                      MethodType.methodType(boolean.class, Object.class));
 96             OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode",
 97                                                        MethodType.fromMethodDescriptorString("()I", loader));

236      * @return the method handle
237      */
238     private static MethodHandle makeHashCode(Class<?> receiverClass,
239                                             List<MethodHandle> getters) {
240         MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I
241 
242         // @@@ Use loop combinator instead?
243         for (MethodHandle getter : getters) {
244             MethodHandle hasher = hasher(getter.type().returnType()); // (T)I
245             MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter);    // (R)I
246             MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I
247             accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I
248         }
249 
250         return accumulator;
251     }
252 
253     /**
254      * Generates a method handle for the {@code toString} method for a given data class
255      * @param receiverClass   the data class
256      * @param simpleName      the simple name of the record class
257      * @param getters         the list of getters
258      * @param names           the names
259      * @return the method handle
260      */
261     private static MethodHandle makeToString(MethodHandles.Lookup lookup,
262                                             Class<?> receiverClass,
263                                             String simpleName,
264                                             MethodHandle[] getters,
265                                             List<String> names) {
266         assert getters.length == names.size();
267         if (getters.length == 0) {
268             // special case
269             MethodHandle emptyRecordCase = MethodHandles.constant(String.class, simpleName + "[]");
270             emptyRecordCase = MethodHandles.dropArguments(emptyRecordCase, 0, receiverClass); // (R)S
271             return emptyRecordCase;
272         }
273 
274         boolean firstTime = true;
275         MethodHandle[] mhs;
276         List<List<MethodHandle>> splits;
277         MethodHandle[] toSplit = getters;
278         int namesIndex = 0;
279         do {
280             /* StringConcatFactory::makeConcatWithConstants can only deal with 200 slots, longs and double occupy two
281              * the rest 1 slot, we need to chop the current `getters` into chunks, it could be that for records with
282              * a lot of components that we need to do a couple of iterations. The main difference between the first
283              * iteration and the rest would be on the recipe
284              */
285             splits = split(toSplit);
286             mhs = new MethodHandle[splits.size()];
287             for (int splitIndex = 0; splitIndex < splits.size(); splitIndex++) {
288                 String recipe = "";
289                 if (firstTime && splitIndex == 0) {
290                     recipe = simpleName + "[";
291                 }
292                 for (int i = 0; i < splits.get(splitIndex).size(); i++) {
293                     recipe += firstTime ? names.get(namesIndex) + "=" + "\1" : "\1";
294                     if (firstTime && namesIndex != names.size() - 1) {
295                         recipe += ", ";
296                     }
297                     namesIndex++;
298                 }
299                 if (firstTime && splitIndex == splits.size() - 1) {
300                     recipe += "]";
301                 }
302                 Class<?>[] concatTypeArgs = new Class<?>[splits.get(splitIndex).size()];
303                 // special case: no need to create another getters if there is only one split
304                 MethodHandle[] currentSplitGetters = new MethodHandle[splits.get(splitIndex).size()];
305                 for (int j = 0; j < splits.get(splitIndex).size(); j++) {
306                     concatTypeArgs[j] = splits.get(splitIndex).get(j).type().returnType();
307                     currentSplitGetters[j] = splits.get(splitIndex).get(j);
308                 }
309                 MethodType concatMT = MethodType.methodType(String.class, concatTypeArgs);
310                 try {

399      * @return             a call site if invoked by indy, or a method handle
400      *                     if invoked by a condy
401      * @throws IllegalArgumentException if the bootstrap arguments are invalid
402      *                                  or inconsistent
403      * @throws NullPointerException if any argument is {@code null} or if any element
404      *                              in the {@code getters} array is {@code null}
405      * @throws Throwable if any exception is thrown during call site construction
406      */
407     public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
408                                    Class<?> recordClass,
409                                    String names,
410                                    MethodHandle... getters) throws Throwable {
411         requireNonNull(lookup);
412         requireNonNull(methodName);
413         requireNonNull(type);
414         requireNonNull(recordClass);
415         requireNonNull(names);
416         requireNonNull(getters);
417         Arrays.stream(getters).forEach(Objects::requireNonNull);
418         MethodType methodType;
419         Class<?> receiverType = recordClass.isPrimitiveClass() ? recordClass.asValueType() : recordClass;
420         if (type instanceof MethodType mt) {
421             methodType = mt;
422             if (mt.parameterType(0) != receiverType) {
423                 throw new IllegalArgumentException("Bad method type: " + mt);
424             }
425         } else {
426             methodType = null;
427             if (!MethodHandle.class.equals(type))
428                 throw new IllegalArgumentException(type.toString());
429         }
430         List<MethodHandle> getterList = List.of(getters);
431         for (MethodHandle getter : getterList) {
432             if (getter.type().parameterType(0) != receiverType) {
433                 throw new IllegalArgumentException("Bad receiver type: " + getter);
434             }
435         }
436         MethodHandle handle = switch (methodName) {
437             case "equals"   -> {
438                 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, receiverType, Object.class)))
439                     throw new IllegalArgumentException("Bad method type: " + methodType);
440                 yield makeEquals(receiverType, getterList);
441             }
442             case "hashCode" -> {
443                 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, receiverType)))
444                     throw new IllegalArgumentException("Bad method type: " + methodType);
445                 yield makeHashCode(receiverType, getterList);
446             }
447             case "toString" -> {
448                 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, receiverType)))
449                     throw new IllegalArgumentException("Bad method type: " + methodType);
450                 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
451                 if (nameList.size() != getterList.size())
452                     throw new IllegalArgumentException("Name list and accessor list do not match");
453                 yield makeToString(lookup, receiverType, recordClass.getSimpleName(), getters, nameList);
454             }
455             default -> throw new IllegalArgumentException(methodName);
456         };
457         return methodType != null ? new ConstantCallSite(handle) : handle;
458     }
459 }
< prev index next >