Switch to using VarHandles
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / CodecDataObjectGenerator.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.THIS;
14 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.getField;
15 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.invokeMethod;
16 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.putField;
17
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Maps;
21 import java.lang.invoke.MethodHandles;
22 import java.lang.invoke.MethodHandles.Lookup;
23 import java.lang.invoke.VarHandle;
24 import java.lang.reflect.Method;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Comparator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Objects;
32 import java.util.Optional;
33 import net.bytebuddy.ByteBuddy;
34 import net.bytebuddy.description.field.FieldDescription;
35 import net.bytebuddy.description.method.MethodDescription;
36 import net.bytebuddy.description.type.TypeDefinition;
37 import net.bytebuddy.description.type.TypeDescription;
38 import net.bytebuddy.description.type.TypeDescription.Generic;
39 import net.bytebuddy.dynamic.DynamicType.Builder;
40 import net.bytebuddy.dynamic.scaffold.InstrumentedType;
41 import net.bytebuddy.implementation.Implementation;
42 import net.bytebuddy.implementation.Implementation.Context;
43 import net.bytebuddy.implementation.bytecode.Addition;
44 import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
45 import net.bytebuddy.implementation.bytecode.Multiplication;
46 import net.bytebuddy.implementation.bytecode.StackManipulation;
47 import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
48 import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
49 import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
50 import net.bytebuddy.implementation.bytecode.constant.TextConstant;
51 import net.bytebuddy.implementation.bytecode.member.MethodReturn;
52 import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
53 import net.bytebuddy.jar.asm.Label;
54 import net.bytebuddy.jar.asm.MethodVisitor;
55 import net.bytebuddy.jar.asm.Opcodes;
56 import org.eclipse.jdt.annotation.Nullable;
57 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
58 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
59 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
60 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
61 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
62 import org.opendaylight.yangtools.yang.binding.DataObject;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 /**
67  * Private support for generating {@link CodecDataObject} and {@link AugmentableCodecDataObject} specializations.
68  *
69  * <p>
70  * Code generation here is probably more involved than usual mainly due to the fact we *really* want to express the
71  * strong connection between a generated class and BindingCodecContext in terms of a true constant, which boils down to
72  * {@code private static final NodeContextSupplier NCS}. Having such constants provides significant boost to JITs
73  * ability to optimize code -- especially with inlining and constant propagation.
74  *
75  * <p>
76  * The accessor mapping performance is critical due to users typically not taking care of storing the results acquired
77  * by an invocation, assuming the accessors are backed by a normal field -- which of course is not true, as the results
78  * are lazily computed.
79  *
80  * <p>
81  * The design is such that for a particular structure like:
82  * <pre>
83  *     container foo {
84  *         leaf bar {
85  *             type string;
86  *         }
87  *     }
88  * </pre>
89  * we end up generating a class with the following layout:
90  * <pre>
91  *     public final class Foo$$$codecImpl extends CodecDataObject implements Foo {
92  *         private static final VarHandle getBar$$$V;
93  *         private volatile Object getBar;
94  *
95  *         public Foo$$$codecImpl(NormalizedNodeContainer data) {
96  *             super(data);
97  *         }
98  *
99  *         public Bar getBar() {
100  *             return (Bar) codecMember(getBar$$$V, "bar");
101  *         }
102  *     }
103  * </pre>
104  *
105  * <p>
106  * This strategy minimizes the bytecode footprint and follows the generally good idea of keeping common logic in a
107  * single place in a maintainable form. The glue code is extremely light (~6 instructions), which is beneficial on both
108  * sides of invocation:
109  * - generated method can readily be inlined into the caller
110  * - it forms a call site into which codeMember() can be inlined with VarHandle being constant
111  *
112  * <p>
113  * The second point is important here, as it allows the invocation logic around VarHandle to completely disappear,
114  * becoming synonymous with operations on a field. Even though the field itself is declared as volatile, it is only ever
115  * accessed through helper method using VarHandles -- and those helpers are using relaxed field ordering
116  * of {@code getAcquire()}/{@code setRelease()} memory semantics.
117  *
118  * <p>
119  * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
120  * <ul>
121  *   <li>with {@code String}, which ends up looking up a {@link ValueNodeCodecContext}</li>
122  *   <li>with {@code Class}, which ends up looking up a {@link DataContainerCodecContext}</li>
123  *   <li>with {@code NodeContextSupplier}, which performs a direct load</li>
124  * </ul>
125  * The third mode of operation requires that the object being implemented is not defined in a {@code grouping}, because
126  * it welds the object to a particular namespace -- hence it trades namespace mobility for access speed.
127  *
128  * <p>
129  * The sticky point here is the NodeContextSupplier, as it is a heap object which cannot normally be looked up from the
130  * static context in which the static class initializer operates -- so we need perform some sort of a trick here.
131  * Eventhough ByteBuddy provides facilities for bridging references to type fields, those facilities operate on volatile
132  * fields -- hence they do not quite work for us.
133  *
134  * <p>
135  * Another alternative, which we used in Javassist-generated DataObjectSerializers, is to muck with the static field
136  * using reflection -- which works, but requires redefinition of Field.modifiers, which is something Java 9 complains
137  * about quite noisily.
138  *
139  * <p>
140  * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
141  * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
142  * <ul>
143  * <li>During code generation, the context fields are pointed towards
144  *     {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
145  *     {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
146  *     in the context of a class initializer.</li>
147  * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
148  *     class loading operation. At this point the generator installs itself as the current generator for this thread via
149  *     {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
150  * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
151  *     point the static invocations will be redirect to {@link #resolveNodeContextSupplier(String)} and
152  *     {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
153  * <li>Before returning from the class loading call, the generator will detach itself via
154  *     {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
155  * </ul>
156  *
157  * <p>
158  * This strategy works due to close cooperation with the target ClassLoader, as the entire code generation and loading
159  * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
160  */
161 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
162     // Not reusable definition: we can inline NodeContextSuppliers without a problem
163     private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
164             implements NodeContextSupplierProvider<T> {
165         private final ImmutableMap<Method, NodeContextSupplier> properties;
166
167         Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
168                 final @Nullable Method keyMethod) {
169             super(template, keyMethod);
170             this.properties = requireNonNull(properties);
171         }
172
173         @Override
174         Builder<T> generateGetters(final Builder<T> builder) {
175             Builder<T> tmp = builder;
176             for (Method method : properties.keySet()) {
177                 LOG.trace("Generating for fixed method {}", method);
178                 final String methodName = method.getName();
179                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
180                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
181                     new SupplierGetterMethodImplementation(methodName, retType));
182             }
183             return tmp;
184         }
185
186         @Override
187         ArrayList<Method> getterMethods() {
188             return new ArrayList<>(properties.keySet());
189         }
190
191         @Override
192         public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
193             final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
194                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
195             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
196             return verifyNotNull(found.get().getValue());
197         }
198     }
199
200     // Reusable definition: we have to rely on context lookups
201     private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
202             implements LocalNameProvider<T> {
203         private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
204         private final Map<Method, Class<?>> daoProperties;
205
206         Reusable(final Builder<?> template, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
207                 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
208             super(template, keyMethod);
209             this.simpleProperties = requireNonNull(simpleProperties);
210             this.daoProperties = requireNonNull(daoProperties);
211         }
212
213         @Override
214         Builder<T> generateGetters(final Builder<T> builder) {
215             Builder<T> tmp = builder;
216             for (Method method : simpleProperties.keySet()) {
217                 LOG.trace("Generating for simple method {}", method);
218                 final String methodName = method.getName();
219                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
220                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
221                     new SimpleGetterMethodImplementation(methodName, retType));
222             }
223             for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
224                 final Method method = entry.getKey();
225                 LOG.trace("Generating for structured method {}", method);
226                 final String methodName = method.getName();
227                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
228                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
229                     new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
230             }
231
232             return tmp;
233         }
234
235         @Override
236         ArrayList<Method> getterMethods() {
237             final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
238             ret.addAll(simpleProperties.keySet());
239             ret.addAll(daoProperties.keySet());
240             return ret;
241         }
242
243         @Override
244         public String resolveLocalName(final String methodName) {
245             final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
246                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
247             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
248             return found.get().getValue().getSchema().getQName().getLocalName();
249         }
250     }
251
252     private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
253     private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
254     private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
255     private static final Generic BB_HELPER = TypeDefinition.Sort.describe(ToStringHelper.class);
256     private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
257     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
258
259     private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
260         byte[].class, byte[].class);
261     private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
262         Object.class, Object.class);
263     private static final StackManipulation HELPER_ADD = invokeMethod(ToStringHelper.class, "add",
264         String.class, Object.class);
265
266     private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
267
268     private static final int PROT_FINAL = Opcodes.ACC_PROTECTED | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
269     private static final int PUB_FINAL = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
270
271     private static final Builder<?> CDO;
272     private static final Builder<?> ACDO;
273
274     static {
275         final ByteBuddy bb = new ByteBuddy();
276         CDO = bb.subclass(CodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
277         ACDO = bb.subclass(AugmentableCodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
278     }
279
280     private final Builder<?> template;
281     private final Method keyMethod;
282
283     CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
284         this.template = requireNonNull(template);
285         this.keyMethod = keyMethod;
286     }
287
288     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
289             final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
290             final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
291         return loader.generateClass(bindingInterface, "codecImpl",
292             new Reusable<>(CDO, simpleProperties, daoProperties, keyMethod));
293     }
294
295     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
296             final CodecClassLoader loader, final Class<D> bindingInterface,
297             final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
298             final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
299         return loader.generateClass(bindingInterface, "codecImpl",
300             new Reusable<>(ACDO, simpleProperties, daoProperties, keyMethod));
301     }
302
303     @Override
304     public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
305             final Class<?> bindingInterface) {
306         LOG.trace("Generating class {}", fqcn);
307
308         @SuppressWarnings("unchecked")
309         Builder<T> builder = (Builder<T>) template.name(fqcn).implement(bindingInterface);
310
311         builder = generateGetters(builder);
312
313         if (keyMethod != null) {
314             LOG.trace("Generating for key {}", keyMethod);
315             final String methodName = keyMethod.getName();
316             final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
317             builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
318                 new KeyMethodImplementation(methodName, retType));
319         }
320
321         // Index all property methods, turning them into "getFoo()" invocations, retaining order. We will be using
322         // those invocations in each of the three methods. Note that we do not glue the invocations to 'this', as we
323         // will be invoking them on 'other' in codecEquals()
324         final ArrayList<Method> properties = getterMethods();
325         // Make sure properties are alpha-sorted
326         properties.sort(METHOD_BY_ALPHABET);
327         final ImmutableMap<StackManipulation, Method> methods = Maps.uniqueIndex(properties,
328             ByteBuddyUtils::invokeMethod);
329
330         // Final bits:
331         return GeneratorResult.of(builder
332                 // codecHashCode() ...
333                 .defineMethod("codecHashCode", BB_INT, PROT_FINAL)
334                 .intercept(new Implementation.Simple(new CodecHashCode(methods)))
335                 // ... codecEquals() ...
336                 .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
337                 .intercept(codecEquals(methods))
338                 // ... and codecFillToString() ...
339                 .defineMethod("codecFillToString", BB_HELPER, PROT_FINAL).withParameter(BB_HELPER)
340                 .intercept(codecFillToString(methods))
341                 // ... and build it
342                 .make());
343     }
344
345     abstract Builder<T> generateGetters(Builder<T> builder);
346
347     abstract ArrayList<Method> getterMethods();
348
349     private static Implementation codecEquals(final ImmutableMap<StackManipulation, Method> properties) {
350         // Label for 'return false;'
351         final Label falseLabel = new Label();
352         // Condition for 'if (!...)'
353         final StackManipulation ifFalse = ByteBuddyUtils.ifEq(falseLabel);
354
355         final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 6 + 5);
356         for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
357             // if (!java.util.(Objects|Arrays).equals(getFoo(), other.getFoo())) {
358             //     return false;
359             // }
360             manipulations.add(THIS);
361             manipulations.add(entry.getKey());
362             manipulations.add(FIRST_ARG_REF);
363             manipulations.add(entry.getKey());
364             manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_EQUALS : OBJECTS_EQUALS);
365             manipulations.add(ifFalse);
366         }
367
368         // return true;
369         manipulations.add(IntegerConstant.ONE);
370         manipulations.add(MethodReturn.INTEGER);
371         // L0: return false;
372         manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
373         manipulations.add(IntegerConstant.ZERO);
374         manipulations.add(MethodReturn.INTEGER);
375
376         return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
377     }
378
379     private static Implementation codecFillToString(final ImmutableMap<StackManipulation, Method> properties) {
380         final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 4 + 2);
381         // push 'return helper' to stack...
382         manipulations.add(FIRST_ARG_REF);
383         for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
384             // .add("getFoo", getFoo())
385             manipulations.add(new TextConstant(entry.getValue().getName()));
386             manipulations.add(THIS);
387             manipulations.add(entry.getKey());
388             manipulations.add(HELPER_ADD);
389         }
390         // ... execute 'return helper'
391         manipulations.add(MethodReturn.REFERENCE);
392
393         return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
394     }
395
396     private abstract static class AbstractMethodImplementation implements Implementation {
397         private static final Generic BB_HANDLE = TypeDefinition.Sort.describe(VarHandle.class);
398         private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
399         private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
400         private static final StackManipulation LOOKUP = invokeMethod(MethodHandles.class, "lookup");
401         private static final StackManipulation FIND_VAR_HANDLE = invokeMethod(Lookup.class,
402             "findVarHandle", Class.class, String.class, Class.class);
403
404         static final int PRIV_CONST = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
405                 | Opcodes.ACC_SYNTHETIC;
406         private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
407
408         final TypeDescription retType;
409         // getFoo
410         final String methodName;
411         // getFoo$$$V
412         final String handleName;
413
414         AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
415             this.methodName = requireNonNull(methodName);
416             this.retType = requireNonNull(retType);
417             this.handleName = methodName + "$$$V";
418         }
419
420         @Override
421         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
422             final InstrumentedType tmp = instrumentedType
423                     // private static final VarHandle getFoo$$$V;
424                     .withField(new FieldDescription.Token(handleName, PRIV_CONST, BB_HANDLE))
425                     // private volatile Object getFoo;
426                     .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
427
428             return tmp.withInitializer(new ByteCodeAppender.Simple(
429                 // TODO: acquiring lookup is expensive, we should share it across all initialization
430                 // getFoo$$$V = MethodHandles.lookup().findVarHandle(This.class, "getFoo", Object.class);
431                 LOOKUP,
432                 ClassConstant.of(tmp),
433                 new TextConstant(methodName),
434                 OBJECT_CLASS,
435                 FIND_VAR_HANDLE,
436                 putField(tmp, handleName)));
437         }
438     }
439
440     private static final class KeyMethodImplementation extends AbstractMethodImplementation {
441         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
442             "codecKey", VarHandle.class);
443
444         KeyMethodImplementation(final String methodName, final TypeDescription retType) {
445             super(methodName, retType);
446         }
447
448         @Override
449         public ByteCodeAppender appender(final Target implementationTarget) {
450             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
451             return new ByteCodeAppender.Simple(
452                 // return (FooType) codecKey(getFoo$$$V);
453                 THIS,
454                 getField(instrumentedType, handleName),
455                 CODEC_KEY,
456                 TypeCasting.to(retType),
457                 MethodReturn.REFERENCE);
458         }
459     }
460
461     /*
462      * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
463      * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
464      * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
465      * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
466      * on the constant pool entry to resolve to the same object.
467      */
468     private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
469         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
470             "codecMember", VarHandle.class, String.class);
471         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
472             "resolveLocalName", String.class);
473         private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
474
475         // getFoo$$$S
476         private final String stringName;
477
478         SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
479             super(methodName, retType);
480             this.stringName = methodName + "$$$S";
481         }
482
483         @Override
484         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
485             final InstrumentedType tmp = super.prepare(instrumentedType)
486                     // private static final String getFoo$$$S;
487                     .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
488
489             return tmp.withInitializer(new ByteCodeAppender.Simple(
490                 // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
491                 new TextConstant(methodName),
492                 BRIDGE_RESOLVE,
493                 putField(tmp, stringName)));
494         }
495
496         @Override
497         public ByteCodeAppender appender(final Target implementationTarget) {
498             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
499             return new ByteCodeAppender.Simple(
500                 // return (FooType) codecMember(getFoo$$$V, getFoo$$$S);
501                 THIS,
502                 getField(instrumentedType, handleName),
503                 getField(instrumentedType, stringName),
504                 CODEC_MEMBER,
505                 TypeCasting.to(retType),
506                 MethodReturn.REFERENCE);
507         }
508     }
509
510     private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
511         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
512             "codecMember", VarHandle.class, Class.class);
513
514         private final Class<?> bindingClass;
515
516         StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
517                 final Class<?> bindingClass) {
518             super(methodName, retType);
519             this.bindingClass = requireNonNull(bindingClass);
520         }
521
522         @Override
523         public ByteCodeAppender appender(final Target implementationTarget) {
524             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
525             return new ByteCodeAppender.Simple(
526                 // return (FooType) codecMember(getFoo$$$V, FooType.class);
527                 THIS,
528                 getField(instrumentedType, handleName),
529                 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
530                 CODEC_MEMBER,
531                 TypeCasting.to(retType),
532                 MethodReturn.REFERENCE);
533         }
534     }
535
536     private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
537         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
538             "codecMember", VarHandle.class, NodeContextSupplier.class);
539         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
540             "resolveNodeContextSupplier", String.class);
541         private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
542
543         // getFoo$$$C
544         private final String contextName;
545
546         SupplierGetterMethodImplementation(final String methodName, final TypeDescription retType) {
547             super(methodName, retType);
548             contextName = methodName + "$$$C";
549         }
550
551         @Override
552         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
553             final InstrumentedType tmp = super.prepare(instrumentedType)
554                     // private static final NodeContextSupplier getFoo$$$C;
555                     .withField(new FieldDescription.Token(contextName, PRIV_CONST, BB_NCS));
556
557             return tmp.withInitializer(new ByteCodeAppender.Simple(
558                 // getFoo$$$C = CodecDataObjectBridge.resolve("getFoo");
559                 new TextConstant(methodName),
560                 BRIDGE_RESOLVE,
561                 putField(tmp, contextName)));
562         }
563
564         @Override
565         public ByteCodeAppender appender(final Target implementationTarget) {
566             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
567             return new ByteCodeAppender.Simple(
568                 // return (FooType) codecMember(getFoo$$$V, getFoo$$$C);
569                 THIS,
570                 getField(instrumentedType, handleName),
571                 getField(instrumentedType, contextName),
572                 CODEC_MEMBER,
573                 TypeCasting.to(retType),
574                 MethodReturn.REFERENCE);
575         }
576     }
577
578     private static final class CodecHashCode implements ByteCodeAppender {
579         private static final StackManipulation THIRTY_ONE = IntegerConstant.forValue(31);
580         private static final StackManipulation LOAD_RESULT = MethodVariableAccess.INTEGER.loadFrom(1);
581         private static final StackManipulation STORE_RESULT = MethodVariableAccess.INTEGER.storeAt(1);
582         private static final StackManipulation ARRAYS_HASHCODE = invokeMethod(Arrays.class, "hashCode", byte[].class);
583         private static final StackManipulation OBJECTS_HASHCODE = invokeMethod(Objects.class, "hashCode", Object.class);
584
585         private final ImmutableMap<StackManipulation, Method> properties;
586
587         CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
588             this.properties = requireNonNull(properties);
589         }
590
591         @Override
592         public Size apply(final MethodVisitor methodVisitor, final Context implementationContext,
593                 final MethodDescription instrumentedMethod) {
594             final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 8 + 4);
595             // int result = 1;
596             manipulations.add(IntegerConstant.ONE);
597             manipulations.add(STORE_RESULT);
598
599             for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
600                 // result = 31 * result + java.util.(Objects,Arrays).hashCode(getFoo());
601                 manipulations.add(THIRTY_ONE);
602                 manipulations.add(LOAD_RESULT);
603                 manipulations.add(Multiplication.INTEGER);
604                 manipulations.add(THIS);
605                 manipulations.add(entry.getKey());
606                 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_HASHCODE : OBJECTS_HASHCODE);
607                 manipulations.add(Addition.INTEGER);
608                 manipulations.add(STORE_RESULT);
609             }
610             // return result;
611             manipulations.add(LOAD_RESULT);
612             manipulations.add(MethodReturn.INTEGER);
613
614             StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
615                     .apply(methodVisitor, implementationContext);
616             return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);
617         }
618     }
619 }