-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathValueObjectMethods.java
1406 lines (1284 loc) · 63.7 KB
/
ValueObjectMethods.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.runtime;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import jdk.internal.access.JavaLangInvokeAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.value.LayoutIteration;
import sun.invoke.util.Wrapper;
import static java.lang.invoke.MethodHandles.constant;
import static java.lang.invoke.MethodHandles.dropArguments;
import static java.lang.invoke.MethodHandles.filterArguments;
import static java.lang.invoke.MethodHandles.foldArguments;
import static java.lang.invoke.MethodHandles.guardWithTest;
import static java.lang.invoke.MethodHandles.permuteArguments;
import static java.lang.invoke.MethodType.methodType;
import static java.lang.runtime.ObjectMethods.primitiveEquals;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
/**
* Implementation for Object::equals and Object::hashCode for value objects.
*
* ValueObjectMethods::isSubstitutable and valueObjectHashCode are
* private entry points called by VM.
*/
final class ValueObjectMethods {
private ValueObjectMethods() {}
private static final boolean VERBOSE =
System.getProperty("value.bsm.debug") != null;
private static final int MAX_NODE_VISITS =
Integer.getInteger("jdk.value.recursion.threshold", Integer.MAX_VALUE);
private static final JavaLangInvokeAccess JLIA = SharedSecrets.getJavaLangInvokeAccess();
static class MethodHandleBuilder {
private static final HashMap<Class<?>, MethodHandle> primitiveSubstitutable = new HashMap<>();
static {
primitiveSubstitutable.putAll(primitiveEquals); // adopt all the primitive eq methods
primitiveSubstitutable.put(float.class,
findStatic("eqValue", methodType(boolean.class, float.class, float.class)));
primitiveSubstitutable.put(double.class,
findStatic("eqValue", methodType(boolean.class, double.class, double.class)));
}
static Stream<MethodHandle> getterStream(Class<?> type, Comparator<MethodHandle> comparator) {
// filter static fields
List<MethodHandle> mhs = LayoutIteration.ELEMENTS.get(type);
if (comparator != null) {
mhs = new ArrayList<>(mhs);
mhs.sort(comparator);
}
return mhs.stream();
}
static MethodHandle hashCodeForType(Class<?> type) {
if (type.isPrimitive()) {
int index = Wrapper.forPrimitiveType(type).ordinal();
return HASHCODE[index];
} else {
return HASHCODE[Wrapper.OBJECT.ordinal()].asType(methodType(int.class, type));
}
}
static MethodHandle builtinPrimitiveSubstitutable(Class<?> type) {
return primitiveSubstitutable.get(type);
}
/*
* Produces a MethodHandle that returns boolean if two instances
* of the given reference type are substitutable.
*
* Two values of reference type are substitutable i== iff
* 1. if o1 and o2 are both reference objects then o1 r== o2; or
* 2. if o1 and o2 are both values then o1 v== o2
*
* At invocation time, it needs a dynamic check on the objects and
* do the substitutability test if they are of a value class.
*/
static MethodHandle referenceTypeEquals(Class<?> type) {
return OBJECT_EQUALS.asType(methodType(boolean.class, type, type));
}
static Class<?> fieldType(MethodHandle getter) {
Class<?> ftype = getter.type().returnType();
return ftype;
}
private static List<Class<?>> valueTypeFields(Class<?> type) {
return LayoutIteration.ELEMENTS.get(type).stream()
.<Class<?>>map(mh -> mh.type().returnType())
.filter(Class::isValue)
.distinct()
.toList();
}
/*
* Produces a MethodHandle that returns boolean if two value objects
* are substitutable. The method type is (V, V)boolean.
*/
static MethodHandle valueTypeEquals(Class<?> type) {
var builder = METHOD_HANDLE_BUILDERS.get(type);
if (builder == null) {
builder = newBuilder(type);
}
return builder.equalsTarget();
}
/*
* Produces a MethodHandle that computes the hash code of a value object.
* The method type of the return MethodHandle is (V)int.
*/
static MethodHandle valueTypeHashCode(Class<?> type) {
var builder = METHOD_HANDLE_BUILDERS.get(type);
if (builder == null) {
builder = newBuilder(type);
}
return builder.hashCodeTarget();
}
/*
* Produces a MethodHandle that returns boolean if the given non-recursively typed
* fields of the two value objects are substitutable. The method type is (V, V)boolean
*/
static MethodHandle valueTypeEquals(Class<?> type, List<MethodHandle> getters) {
assert type.isValue();
MethodType mt = methodType(boolean.class, type, type);
MethodHandle instanceTrue = dropArguments(TRUE, 0, type, Object.class).asType(mt);
MethodHandle instanceFalse = dropArguments(FALSE, 0, type, Object.class).asType(mt);
MethodHandle accumulator = dropArguments(TRUE, 0, type, type);
for (MethodHandle getter : getters) {
Class<?> ftype = fieldType(getter);
var eq = substitutableInvoker(ftype).asType(methodType(boolean.class, ftype, ftype));
var thisFieldEqual = filterArguments(eq, 0, getter, getter);
accumulator = guardWithTest(thisFieldEqual, accumulator, instanceFalse);
}
// if both arguments are null, return true;
// otherwise return accumulator;
return guardWithTest(IS_NULL.asType(mt),
instanceTrue,
guardWithTest(IS_SAME_VALUE_CLASS.asType(mt),
accumulator,
instanceFalse));
}
/*
* Produces a MethodHandle that returns the hash code computed from
* the given non-recursively-typed fields of a value object.
* The method type is (V)int.
*/
static MethodHandle valueTypeHashCode(Class<?> type, List<MethodHandle> getters) {
assert type.isValue();
MethodHandle target = dropArguments(constant(int.class, SALT), 0, type);
MethodHandle classHasher = dropArguments(hashCodeForType(Class.class).bindTo(type), 0, type);
MethodHandle hashCombiner = dropArguments(HASH_COMBINER, 2, type);
MethodHandle accumulator = foldArguments(foldArguments(hashCombiner, 1, classHasher), 0, target);
for (MethodHandle getter : getters) {
Class<?> ft = fieldType(getter);
// For primitive types or reference types, this calls Objects::hashCode.
// For value objects and the hashCode method is not overridden,
// VM will call valueObjectHashCode to compute the hash code.
var hasher = hashCodeForType(ft);
var hashThisField = filterArguments(hasher, 0, getter); // (R)I
var combineHashes = foldArguments(hashCombiner, 1, hashThisField);
accumulator = foldArguments(combineHashes, 0, accumulator);
}
return accumulator;
}
// ------ utility methods ------
private static boolean eq(Object a, Object b) {
if (a == null && b == null) return true;
if (a == null || b == null) return false;
if (a.getClass() != b.getClass()) return false;
return a.getClass().isValue() ? valueEquals(a, b) : (a == b);
}
/*
* Returns true if two value objects are substitutable.
*/
private static boolean valueEquals(Object a, Object b) {
assert a != null && b != null && isSameValueClass(a, b);
try {
Class<?> type = a.getClass();
return (boolean) substitutableInvoker(type).invoke(type.cast(a), type.cast(b));
} catch (Error|RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new InternalError(e);
}
}
private static boolean isNull(Object a, Object b) {
// avoid acmp that will call isSubstitutable
if (a != null) return false;
if (b != null) return false;
return true;
}
/*
* Returns true if the given objects are of the same value class.
*
* Two objects are of the same value class iff:
* 1. a != null and b != null
* 2. the declaring class of a and b is the same value class
*/
private static boolean isSameValueClass(Object a, Object b) {
if (a == null || b == null) return false;
return a.getClass().isValue() && a.getClass() == b.getClass();
}
private static int hashCombiner(int accumulator, int value) {
return accumulator * 31 + value;
}
private static int[] newCounter(int[] counter) {
return new int[] { counter[0] };
}
private static boolean recurValueEq(MethodHandle target, Object o1, Object o2, int[] counter) {
assert counter[0] > 0;
if (o1 == null && o2 == null) return true;
if (o1 == null || o2 == null) return false;
if (o1.getClass() != o2.getClass()) return false;
if (--counter[0] == 0) {
throw new StackOverflowError("fail to evaluate == for value class " + o1.getClass().getName());
}
try {
return (boolean) target.invoke(o1, o2, counter);
} catch (Error|RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new InternalError(e);
}
}
private static int recurValueHashCode(MethodHandle target, Object o, int[] counter) {
assert counter[0] > 0;
if (o == null) return 0;
if (--counter[0] == 0) {
throw new StackOverflowError("fail to evaluate hashCode for value class " + o.getClass().getName());
}
try {
return (int) target.invoke(o, counter);
} catch (Error|RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new InternalError(e);
}
}
private static final MethodHandle FALSE = constant(boolean.class, false);
private static final MethodHandle TRUE = constant(boolean.class, true);
// Substitutability test for float
private static boolean eqValue(float a, float b) {
return Float.floatToRawIntBits(a) == Float.floatToRawIntBits(b);
}
// Substitutability test for double
private static boolean eqValue(double a, double b) {
return Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b);
}
private static final MethodHandle OBJECT_EQUALS =
findStatic("eq", methodType(boolean.class, Object.class, Object.class));
private static final MethodHandle IS_SAME_VALUE_CLASS =
findStatic("isSameValueClass", methodType(boolean.class, Object.class, Object.class));
private static final MethodHandle IS_NULL =
findStatic("isNull", methodType(boolean.class, Object.class, Object.class));
private static final MethodHandle HASH_COMBINER =
findStatic("hashCombiner", methodType(int.class, int.class, int.class));
private static final MethodHandle[] HASHCODE = initHashCode();
private static final MethodHandle RECUR_VALUE_EQ =
findStatic("recurValueEq", methodType(boolean.class, MethodHandle.class, Object.class, Object.class, int[].class));
private static final MethodHandle RECUR_VALUE_HASHCODE =
findStatic("recurValueHashCode", methodType(int.class, MethodHandle.class, Object.class, int[].class));
private static final MethodHandle NEW_COUNTER =
findStatic("newCounter", methodType(int[].class, int[].class));
private static MethodHandle[] initHashCode() {
MethodHandle[] mhs = new MethodHandle[Wrapper.COUNT];
for (Wrapper wrapper : Wrapper.values()) {
if (wrapper == Wrapper.VOID) continue;
Class<?> cls = wrapper == Wrapper.OBJECT ? Objects.class : wrapper.wrapperType();
mhs[wrapper.ordinal()] = findStatic(cls, "hashCode",
methodType(int.class, wrapper.primitiveType()));
}
return mhs;
}
private static MethodHandle findStatic(String name, MethodType methodType) {
return findStatic(MethodHandleBuilder.class, name, methodType);
}
private static MethodHandle findStatic(Class<?> cls, String name, MethodType methodType) {
try {
return JLIA.findStatic(cls, name, methodType);
} catch (IllegalAccessException e) {
throw newLinkageError(e);
}
}
/**
* A "salt" value used for this internal hashcode implementation that
* needs to vary sufficiently from one run to the next so that
* the default hashcode for value classes will vary between JVM runs.
*/
static final int SALT;
static {
long nt = System.nanoTime();
int value = (int)((nt >>> 32) ^ nt);
SALT = Integer.getInteger("value.bsm.salt", value);
}
static MethodHandleBuilder newBuilder(Class<?> type) {
assert type.isValue();
Deque<Class<?>> deque = new ArrayDeque<>();
deque.add(type);
Map<Class<?>, MethodHandleBuilder> visited = new HashMap<>();
var builder = new MethodHandleBuilder(type, deque, visited);
visited.put(type, builder);
return builder;
}
enum Status {
NOT_START,
IN_PROGRESS,
TRAVERSAL_DONE,
READY
}
final Class<?> type;
final List<Class<?>> fieldValueTypes;
// a map of the type of a field T to a cycle of T -> ... -> V
// where V is this builder's value type
final Map<Class<?>, List<Class<?>>> cyclicMembers = new HashMap<>();
// recursively-typed fields declared in this builder's value type
final Set<Class<?>> recurFieldTypes = new HashSet<>();
final Deque<Class<?>> path;
final Map<Class<?>, MethodHandleBuilder> visited;;
volatile Status status = Status.NOT_START;
volatile MethodHandle equalsTarget;
volatile MethodHandle hashCodeTarget;
static final VarHandle STATUS_HANDLE;
static {
VarHandle vh = null;
try {
vh = MethodHandles.lookup().findVarHandle(MethodHandleBuilder.class, "status", Status.class);
} catch (ReflectiveOperationException e) {
throw new InternalError(e);
}
STATUS_HANDLE = vh;
}
/**
* Constructs a new MethodHandleBuilder for the given value type.
*
* @param type a value class
* @param path the graph traversal
* @param visited a map of a visited type to a builder
*/
private MethodHandleBuilder(Class<?> type, Deque<Class<?>> path, Map<Class<?>, MethodHandleBuilder> visited) {
this.type = type;
this.fieldValueTypes = valueTypeFields(type);
this.path = path;
this.visited = visited;
if (VERBOSE) {
System.out.println("New builder for " + type.getName() + " " + path);
}
}
/*
* Returns a method handle that implements equals method for this builder's value class.
*/
MethodHandle equalsTarget() {
if (status != Status.READY)
throw new IllegalStateException(type.getName() + " not ready");
var mh = equalsTarget;
if (mh != null) return mh;
generateMethodHandle();
return equalsTarget;
}
/*
* Returns a method handle that implements hashCode method for this builder's value class.
*/
MethodHandle hashCodeTarget() {
if (status != Status.READY)
throw new IllegalStateException(type.getName() + " not ready");
var mh = hashCodeTarget;
if (mh != null) return mh;
generateMethodHandle();
return hashCodeTarget;
}
/*
* Build the graph for this builder's value type. Detect all cycles.
* This builder after this method returns is in DONE_TRAVERSAL or READY status.
*
* A builder for type V will change to READY status when the entire graph for V
* is traversed (i.e. all builders in this graph are in DONE_TRAVERSAL or READY
* status).
*/
MethodHandleBuilder build() {
if (status == Status.READY) return this;
if (!STATUS_HANDLE.compareAndSet(this, Status.NOT_START, Status.IN_PROGRESS)) {
throw new RuntimeException(type.getName() + " in progress");
}
// traverse the graph and find all cycles
detectCycles();
if (!STATUS_HANDLE.compareAndSet(this, Status.IN_PROGRESS, Status.TRAVERSAL_DONE)) {
throw new RuntimeException(type.getName() + " failed to set done traversal. " + status);
}
// Check if this node V is ready for building equals/hashCode method handles.
// V is ready if the types of all its fields are done traversal.
if (ready()) {
// Do a pass on all the cycles containing V. V is ready.
// If a node N in the cycle has completed the traversal (i.e. cycles are detected),
// call ready() on N to update its status if ready.
for (List<Class<?>> cycle : cyclicMembers.values()) {
cycle.stream().filter(c -> c != type)
.map(visited::get)
.filter(b -> b.status == Status.TRAVERSAL_DONE)
.forEach(MethodHandleBuilder::ready);
}
}
return this;
}
/*
* Traverses the graph and finds all cycles.
*/
private void detectCycles() {
LinkedList<Class<?>> deque = new LinkedList<>();
deque.addAll(fieldValueTypes);
while (!deque.isEmpty()) {
Class<?> n = deque.pop();
// detect cyclic membership
if (path.contains(n)) {
List<Class<?>> cycle = new ArrayList<>();
Iterator<Class<?>> iter = path.iterator();
while (iter.hasNext()) {
Class<?> c = iter.next();
cycle.add(c);
if (c == n) break;
}
cyclicMembers.put(n, cycle);
path.pop();
continue;
}
try {
path.push(n);
if (!visited.containsKey(n)) {
// Duplicate the path and pass it to an unvisited node
Deque<Class<?>> newPath = new ArrayDeque<>();
newPath.addAll(path);
visited.computeIfAbsent(n, c -> new MethodHandleBuilder(n, newPath, visited));
}
var builder = visited.get(n);
switch (builder.status) {
case NOT_START -> builder.build();
case TRAVERSAL_DONE -> builder.ready();
}
} finally {
path.pop();
}
}
// propagate the cycles to the recursively-typed value classes
// For each cycle A -> B -> C -> A, the cycle is recorded in all
// the nodes (A, B, and C) in this cycle.
for (Map.Entry<Class<?>, List<Class<?>>> e : cyclicMembers.entrySet()) {
Class<?> c = e.getKey();
List<Class<?>> cycle = e.getValue();
var builder = visited.get(c);
for (Class<?> ft : cycle) {
if (ft != c && builder.fieldValueTypes.contains(ft)) {
var v = builder.cyclicMembers.put(ft, cycle);
assert v == null || cycle.equals(v) : "mismatched cycle: " + v + " vs " + cycle;
}
}
}
}
/*
* Tests if this builder is ready for generating equals and hashCode
* method handles for the value class.
*
* This builder is ready if and only if the type graph of all its fields
* are traversed and all cycles are detected.
*
* Before setting to READY, the recursively-typed fields are recorded
* that includes all types in the cycles and the field types which
* references recursive types
*/
private boolean ready() {
if (status == Status.READY) return true;
boolean inProgress = fieldValueTypes.stream().map(visited::get)
.anyMatch(b -> b.status == Status.IN_PROGRESS);
if (inProgress)
return false;
// collect the recursively-typed value classes required by this method handle
// all types in the cycles and the field types which references recursive types
recurFieldTypes.addAll(cyclicMembers.keySet());
for (Class<?> c : fieldValueTypes) {
if (c == type) continue;
// if this field type references a recursive type
var b = visited.get(c);
if (b.cyclicMembers.size() > 0 || b.recurFieldTypes.size() > 0)
recurFieldTypes.add(c);
};
// Finished recording recursively-typed fields. Set to READY.
if (!STATUS_HANDLE.compareAndSet(this, Status.TRAVERSAL_DONE, Status.READY)) {
throw new RuntimeException(type.getName() + " failed to set READY. " + status);
}
return true;
}
void generateMethodHandle() {
if (status != Status.READY)
throw new IllegalStateException(type.getName() + " not ready");
// non-recursive value type
if (recurFieldTypes.isEmpty()) {
if (cyclicMembers.size() > 0)
throw new RuntimeException(type.getName() + " should not reach here");
this.equalsTarget = valueTypeEquals(type, getterStream(type, TYPE_SORTER).toList());
this.hashCodeTarget = valueTypeHashCode(type, getterStream(type, null).toList());
return;
}
if (VERBOSE) {
System.out.println(debugString());
}
// generate the base function for each recursive type
// boolean base1(MethodHandle entry, MethodHandle base1, MethodHandle base2,....., Object o1, Object o2, int[] counter)
// :
// boolean baseN(MethodHandle entry, MethodHandle base1, MethodHandle base2,....., Object o1, Object o2, int[] counter)
//
List<Class<?>> recursiveTypes = aggregateRecursiveTypes();
Map<Class<?>, MethodHandle> bases = new LinkedHashMap<>();
Map<Class<?>, MethodHandle> hashCodeBases = new LinkedHashMap<>();
for (Class<?> c : recursiveTypes) {
bases.put(c, visited.get(c).generateSubstBase(recursiveTypes));
hashCodeBases.put(c, visited.get(c).generateHashCodeBase(recursiveTypes));
}
var handles = bases.values().stream().toArray(MethodHandle[]::new);
var hashCodeHandles = hashCodeBases.values().stream().toArray(MethodHandle[]::new);
// The entry point for equals for this value type T looks like this:
//
// boolean entry(MethodHandle entry, MethodHandle base1, MethodHandle base2,....., Object o1, Object o2, int[] counter) {
// int[] newCounter = new int[] { counter[0] } ;
// return baseT(o1, o2, newCounter);
// }
this.equalsTarget = newValueEquals(recursiveTypes, handles);
this.hashCodeTarget = newValueHashCode(recursiveTypes, hashCodeHandles);
// Precompute the method handles for all recursive data types in the cycles
// They share the generated base method handles.
var cycles = cyclicMembers.values().stream().flatMap(List::stream)
.filter(c -> c != type)
.collect(toMap(Function.identity(), visited::get));
for (Class<?> n : cycles.keySet()) {
var builder = cycles.get(n);
if (builder.status != Status.READY) {
throw new InternalError(type.getName() + " is not ready: " + status);
}
var mh = builder.equalsTarget;
var mh2 = builder.hashCodeTarget;
if (mh != null && mh2 != null) {
continue;
}
// precompute the method handles for each recursive type in the cycle
if (mh == null) {
builder.equalsTarget = builder.newValueEquals(recursiveTypes, handles);
}
if (mh2 == null) {
builder.hashCodeTarget = builder.newValueHashCode(recursiveTypes, hashCodeHandles);
}
}
// cache the builders with precomputed method handles in the cache
synchronized (CACHED_METHOD_HANDLE_BUILDERS) {
for (Class<?> n : cycles.keySet()) {
try {
// the builder is added to the builder cache and propapate to
// the class value
CACHED_METHOD_HANDLE_BUILDERS.computeIfAbsent(n, cycles::get);
METHOD_HANDLE_BUILDERS.get(n);
} finally {
// Remove it from the builder cache once it's in class value
CACHED_METHOD_HANDLE_BUILDERS.remove(n);
}
}
}
// equals and hashCode are generated. Clear the path and visited builders.
clear();
}
private void clear() {
path.clear();
visited.clear();
}
/*
* Aggregates all recursive data types for this builder's value types.
* The result is used in generating a recursive method handle
* for this builder's value type.
*
* A graph of V:
* V -> P -> V
* -> N -> N (self-recursive)
* -> E -> F -> E
*
* V, P, N, E, F are the mutual recursive types for V. The recursive method handle
* for V is created with the base functions for V, P, N, E, F and it can mutually
* call the recursive method handle for these types. Specifically, MH_V calls
* MH_P which calls MH_V, MH_N which calls itself, and MH_E which calls MH_F.
*/
private List<Class<?>> aggregateRecursiveTypes() {
boolean ready = true;
for (List<Class<?>> cycle : cyclicMembers.values()) {
// ensure all nodes in all cycles that are done traversal and ready for
// method handle generation
cycle.stream().filter(c -> c != type)
.map(visited::get)
.filter(b -> b.status == Status.TRAVERSAL_DONE)
.forEach(MethodHandleBuilder::ready);
// check the status
ready = ready && cycle.stream().filter(c -> c != type)
.map(visited::get)
.allMatch(b -> b.status == Status.READY);
}
if (!ready) {
throw new IllegalStateException(type.getName() + " " + status);
}
/*
* Traverse the graph for V to find all mutual recursive types for V.
*
* Node T is a mutual recursive type for V if any of the following:
* 1. T is a recursively-typed field in V
* 2. T is a type involved the cycles from V ... -> T ... -> V
* 3. T is a mutual recursive type for N where N is a mutual recursive type for V.
*/
Deque<Class<?>> deque = new ArrayDeque<>();
List<Class<?>> recurTypes = new ArrayList<>();
recurTypes.add(type);
Stream.concat(recurFieldTypes.stream(),
cyclicMembers.values().stream().flatMap(List::stream))
.filter(Predicate.not(deque::contains)).forEach(deque::add);
while (!deque.isEmpty()) {
Class<?> c = deque.pop();
if (recurTypes.contains(c)) continue;
recurTypes.add(c);
var builder = visited.get(c);
Stream.concat(builder.recurFieldTypes.stream(),
builder.cyclicMembers.values().stream().flatMap(List::stream))
.filter(n -> !recurTypes.contains(n) && !deque.contains(n))
.forEach(deque::push);
}
return recurTypes;
}
/*
* Create a new method handle that implements equals(T, Object) for value class T
* for this builder using the given base method handles. The return method handle
* is capable of recursively calling itself for value class T whose entry point:
* boolean entry(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., Object o1, Object o2, int[] counter) {
* int[] newCounter = new int[] { counter[0] };
* return baseT(o1, o2, newCounter);
* }
*
* The counter is used to keep of node visits and throw StackOverflowError
* if the counter gets "unreasonably" large of a cyclic value graph
* (regardless of how many real stack frames were consumed.)
*/
MethodHandle newValueEquals(List<Class<?>> recursiveTypes, MethodHandle[] bases) {
var entry = equalsEntry(recursiveTypes);
var mh = MethodHandles.insertArguments(recursive(entry, bases), 2, new int[] {MAX_NODE_VISITS});
return mh.asType(methodType(boolean.class, type, type));
}
/*
* Create a new method handle that implements hashCode(T) for value class T
* for this builder using the given base method handles. The return method handle
* is capable of recursively calling itself for value class T whose entry point:
* boolean entry(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., Object o, int[] counter) {
* int[] newCounter = new int[] { counter[0] };
* return baseT(o, newCounter);
* }
*
* The counter is used to keep of node visits and throw StackOverflowError
* if the counter gets "unreasonably" large of a cyclic value graph
* (regardless of how many real stack frames were consumed.)
*/
MethodHandle newValueHashCode(List<Class<?>> recursiveTypes, MethodHandle[] bases) {
var entry = hashCodeEntry(recursiveTypes);
var mh = MethodHandles.insertArguments(recursive(entry, bases), 1, new int[] {MAX_NODE_VISITS});
return mh.asType(methodType(int.class, type));
}
/*
* Create a method handle where the first N+1 parameters are MethodHandle and
* N is the number of the recursive value types and followed with
* Object, Object and int[] parameters. The pseudo code looks like this:
*
* boolean eq(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., Object o1, Object o2, int[] counter) {
* if (o1 == null && o2 == null) return true;
* if (o1 == null || o2 == null) return false;
* if (o1.getClass() != o2. getClass()) return false;
*
* int[] newCounter = new int[] { counter[0]; }
* return (boolean) baseT.invoke(o1, o2, newCounter);
* }
*/
MethodHandle equalsEntry(List<Class<?>> recursiveTypes) {
List<Class<?>> leadingMHParams = new ArrayList<>();
// the first MethodHandle parameter is this entry point
// followed with MethodHandle parameter for each mutual exclusive value class
int mhParamCount = recursiveTypes.size()+1;
for (int i=0; i < mhParamCount; i++) {
leadingMHParams.add(MethodHandle.class);
}
MethodType mt = methodType(boolean.class, Stream.concat(leadingMHParams.stream(), Stream.of(type, type, int[].class))
.collect(toList()));
var allParameters = mt.parameterList();
MethodHandle instanceTrue = dropArguments(TRUE, 0, allParameters).asType(mt);
MethodHandle instanceFalse = dropArguments(FALSE, 0, allParameters).asType(mt);
MethodHandle isNull = dropArguments(dropArguments(IS_NULL, 0, leadingMHParams), mhParamCount+2, int[].class).asType(mt);
MethodHandle isSameValueType = dropArguments(dropArguments(IS_SAME_VALUE_CLASS, 0, leadingMHParams), mhParamCount+2, int[].class).asType(mt);
int index = recursiveTypes.indexOf(type);
var mtype = methodType(boolean.class, Stream.concat(leadingMHParams.stream(), Stream.of(type, type, int[].class)).collect(toList()));
var recurEq = RECUR_VALUE_EQ.asType(methodType(boolean.class, MethodHandle.class, type, type, int[].class));
var eq = permuteArguments(recurEq, mtype, index+1, mhParamCount, mhParamCount+1, mhParamCount+2);
eq = filterArguments(eq, mhParamCount+2, NEW_COUNTER);
// if both arguments are null, return true;
// otherwise return the method handle corresponding to this type
return guardWithTest(isNull,
instanceTrue,
guardWithTest(isSameValueType, eq, instanceFalse));
}
/*
* A base method for substitutability test for a recursive data type,
* a value class with cyclic membership.
*
* The signature of this base method is:
* boolean base(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., V o1, V o2, int[] counter)
*
* where the first N+1 parameters are MethodHandle and N is the number of
* the recursive value types and followed with Object, Object and int[] parameters.
*
* This method first calls the method handle that tests the substitutability
* of all fields that are not recursively-typed, if any, and then test
* the substitutability of the fields that are of each recursive value type.
* The pseudo code looks like this:
*
* boolean base(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., V o1, V o2, int[] counter) {
* if (o1 == null && o2 == null) return true;
* if (o1 == null || o2 == null) return false;
* if (o1.getClass() != o2. getClass()) return false;
*
* for each non-recursively-typed field {
* if (field value of o1 != field value of o2) return false;
* }
*
* for each recursively-typed field of type T {
* if (--counter[0] == 0) throw new StackOverflowError();
* // baseT is the method handle corresponding to the recursive type T
* boolean rc = (boolean) baseT.invoke(o1, o2, counter);
* if (!rc) return false;
* }
* return true;
* }
*/
MethodHandle generateSubstBase(List<Class<?>> recursiveTypes) {
List<MethodHandle> nonRecurGetters = new ArrayList<>();
Map<Class<?>, List<MethodHandle>> recurGetters = new LinkedHashMap<>();
getterStream(type, TYPE_SORTER).forEach(mh -> {
Class<?> ft = fieldType(mh);
if (!this.recurFieldTypes.contains(ft)) {
nonRecurGetters.add(mh);
} else {
assert recursiveTypes.contains(ft);
recurGetters.computeIfAbsent(ft, t -> new ArrayList<>()).add(mh);
}
});
// The first parameter is the method handle of the entry point
// followed with one MethodHandle for each recursive value type
List<Class<?>> leadingMHParams = new ArrayList<>();
int mhParamCount = recursiveTypes.size()+1;
for (int i=0; i < mhParamCount; i++) {
leadingMHParams.add(MethodHandle.class);
}
MethodType mt = methodType(boolean.class,
Stream.concat(leadingMHParams.stream(), Stream.of(type, type, int[].class)).collect(toList()));
var allParameters = mt.parameterList();
var instanceTrue = dropArguments(TRUE, 0, allParameters).asType(mt);
var instanceFalse = dropArguments(FALSE, 0, allParameters).asType(mt);
var accumulator = dropArguments(TRUE, 0, allParameters).asType(mt);
var isNull = dropArguments(dropArguments(IS_NULL, 0, leadingMHParams), mhParamCount+2, int[].class).asType(mt);
var isSameValueType = dropArguments(dropArguments(IS_SAME_VALUE_CLASS, 0, leadingMHParams), mhParamCount+2, int[].class).asType(mt);
// This value class contains cyclic membership.
// Create a method handle that first calls the method handle that tests
// the substitutability of all fields that are not recursively-typed, if any,
// and then test the substitutability of the fields that are of each recursive
// value type.
//
// Method handle for the substitutability test for recursive types is built
// before that for non-recursive types.
for (Map.Entry<Class<?>, List<MethodHandle>> e : recurGetters.entrySet()) {
Class<?> ft = e.getKey();
int index = recursiveTypes.indexOf(ft);
var mtype = methodType(boolean.class,
Stream.concat(leadingMHParams.stream(), Stream.of(ft, ft, int[].class)).collect(toList()));
var recurEq = RECUR_VALUE_EQ.asType(methodType(boolean.class, MethodHandle.class, ft, ft, int[].class));
var eq = permuteArguments(recurEq, mtype, index+1, mhParamCount, mhParamCount+1, mhParamCount+2);
for (MethodHandle getter : e.getValue()) {
assert ft == fieldType(getter);
var thisFieldEqual = filterArguments(eq, mhParamCount, getter, getter);
accumulator = guardWithTest(thisFieldEqual, accumulator, instanceFalse);
}
}
if (nonRecurGetters.isEmpty()) {
// if both arguments are null, return true;
// otherwise return accumulator;
return guardWithTest(isNull,
instanceTrue,
guardWithTest(isSameValueType, accumulator, instanceFalse));
} else {
// method handle for substitutability test of the non-recursive-typed fields
var mh = valueTypeEquals(type, nonRecurGetters);
mh = dropArguments(dropArguments(mh, 0, leadingMHParams), mhParamCount+2, int[].class).asType(mt);
return guardWithTest(mh, accumulator, instanceFalse);
}
}
/*
* Create a method handle where the first N+1 parameters are MethodHandle and
* N is the number of the recursive value types and followed with
* Object and int[] parameters. The pseudo code looks like this:
*
* int hashCode(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., Object o, int[] counter) {
* int[] newCounter = new int[] { counter[0]; }
* return (int) baseT.invoke(o, newCounter);
* }
*/
MethodHandle hashCodeEntry(List<Class<?>> recursiveTypes) {
List<Class<?>> leadingMHParams = new ArrayList<>();
int mhParamCount = recursiveTypes.size()+1;
// the first MethodHandle parameter is this entry point
// followed with MethodHandle parameter for each mutual exclusive value class
for (int i=0; i < mhParamCount; i++) {
leadingMHParams.add(MethodHandle.class);
}
int index = recursiveTypes.indexOf(type);
var mtype = methodType(int.class, Stream.concat(leadingMHParams.stream(), Stream.of(type, int[].class)).collect(toList()));
var recurHashCode = RECUR_VALUE_HASHCODE.asType(methodType(int.class, MethodHandle.class, type, int[].class));
var mh = permuteArguments(recurHashCode, mtype, index+1, mhParamCount, mhParamCount+1);
return filterArguments(mh, mhParamCount+1, NEW_COUNTER);
}
/**
* A base method for computing the hashcode for a recursive data type,
* a value class with cyclic membership.
*
* The signature of this base method is:
* int base(MethodHandle entry, MethodHandle base1, MethodHandle base2, ..., V o, int[] counter)
*
* where the first N+1 parameters are MethodHandle and N is the number of
* the recursive value types and followed with Object and int[] parameters.
*
* This method will first invoke a method handle to compute the hash code
* of the not recursively-typed fields. Then compute the hash code of the
* remaining recursively-typed fields.
*/
MethodHandle generateHashCodeBase(List<Class<?>> recursiveTypes) {
assert status == Status.READY;
List<MethodHandle> nonRecurGetters = new ArrayList<>();
Map<Class<?>, List<MethodHandle>> recurGetters = new LinkedHashMap<>();
getterStream(type, null).forEach(mh -> {
Class<?> ft = fieldType(mh);
if (!this.recurFieldTypes.contains(ft)) {
nonRecurGetters.add(mh);
} else {
assert recursiveTypes.contains(ft);
recurGetters.computeIfAbsent(ft, t -> new ArrayList<>()).add(mh);
}
});
int mhParamCount = recursiveTypes.size()+1;
List<Class<?>> leadingMHParams = new ArrayList<>();
for (int i=0; i < mhParamCount; i++) { // include entry point
leadingMHParams.add(MethodHandle.class);
}
MethodType mt = methodType(int.class,
Stream.concat(leadingMHParams.stream(), Stream.of(type, int[].class)).collect(toList()));
var allParameters = mt.parameterList();
var hashCombiner = dropArguments(HASH_COMBINER, 2, allParameters);
var salt = dropArguments(constant(int.class, SALT), 0, allParameters);
var classHasher = dropArguments(hashCodeForType(Class.class).bindTo(type), 0, allParameters);
var accumulator = foldArguments(foldArguments(hashCombiner, 1, classHasher), 0, salt);
for (MethodHandle getter : nonRecurGetters) {
Class<?> ft = fieldType(getter);
var hasher = dropArguments(hashCodeForType(ft), 0, leadingMHParams);