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