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