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