0d3a17e1f1a970494e9e071bcfffe90c0b2e0d7c
[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.type.TypeDefinition;
35 import net.bytebuddy.description.type.TypeDescription;
36 import net.bytebuddy.description.type.TypeDescription.ForLoadedType;
37 import net.bytebuddy.description.type.TypeDescription.Generic;
38 import net.bytebuddy.dynamic.DynamicType.Builder;
39 import net.bytebuddy.dynamic.scaffold.InstrumentedType;
40 import net.bytebuddy.implementation.Implementation;
41 import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
42 import net.bytebuddy.implementation.bytecode.StackManipulation;
43 import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
44 import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
45 import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
46 import net.bytebuddy.implementation.bytecode.constant.TextConstant;
47 import net.bytebuddy.implementation.bytecode.member.MethodReturn;
48 import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
49 import net.bytebuddy.jar.asm.Label;
50 import net.bytebuddy.jar.asm.Opcodes;
51 import org.eclipse.jdt.annotation.Nullable;
52 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
53 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
54 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
55 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
56 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
57 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
58 import org.opendaylight.yangtools.yang.binding.DataObject;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * Private support for generating {@link CodecDataObject} and {@link AugmentableCodecDataObject} specializations.
64  *
65  * <p>
66  * Code generation here is probably more involved than usual mainly due to the fact we *really* want to express the
67  * strong connection between a generated class to the extent possible. In most cases (grouping-generated types) this
68  * involves one level of indirection, which is a safe approach. If we are dealing with a type generated outside of a
69  * grouping statement, though, we are guaranteed instantiation-invariance and hence can hard-wire to a runtime-constant
70  * {@link NodeContextSupplier} -- which  provides significant boost to JITs ability to optimize code -- especially with
71  * 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 VarHandle getBar$$$V;
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$$$V, "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  * <ul>
108  *   <li>generated method can readily be inlined into the caller</li>
109  *   <li>it forms a call site into which codeMember() can be inlined with VarHandle being constant</li>
110  * </ul>
111  *
112  * <p>
113  * The second point is important here, as it allows the invocation logic around VarHandle to completely disappear,
114  * becoming synonymous with operations on a field. Even though the field itself is declared as volatile, it is only ever
115  * accessed through helper method using VarHandles -- and those helpers are using relaxed field ordering
116  * of {@code getAcquire()}/{@code setRelease()} memory semantics.
117  *
118  * <p>
119  * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
120  * <ul>
121  *   <li>with {@code String}, which ends up looking up a {@link ValueNodeCodecContext}</li>
122  *   <li>with {@code Class}, which ends up looking up a {@link DataContainerCodecContext}</li>
123  *   <li>with {@code NodeContextSupplier}, which performs a direct load</li>
124  * </ul>
125  * The third mode of operation requires that the object being implemented is not defined in a {@code grouping}, because
126  * it welds the object to a particular namespace -- hence it trades namespace mobility for access speed.
127  *
128  * <p>
129  * The sticky point here is the NodeContextSupplier, as it is a heap object which cannot normally be looked up from the
130  * static context in which the static class initializer operates -- so we need perform some sort of a trick here.
131  * Even though ByteBuddy provides facilities for bridging references to type fields, those facilities operate on
132  * volatile fields -- hence they do not quite work for us.
133  *
134  * <p>
135  * Another alternative, which we used in Javassist-generated DataObjectSerializers, is to muck with the static field
136  * using reflection -- which works, but requires redefinition of Field.modifiers, which is something Java 9+ complains
137  * about quite noisily.
138  *
139  * <p>
140  * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
141  * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
142  * <ul>
143  * <li>During code generation, the context fields are pointed towards
144  *     {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
145  *     {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
146  *     in the context of a class initializer.</li>
147  * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
148  *     class loading operation. At this point the generator installs itself as the current generator for this thread via
149  *     {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
150  * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
151  *     point the static invocations will be redirected to {@link #resolveNodeContextSupplier(String)} and
152  *     {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
153  * <li>Before returning from the class loading call, the generator will detach itself via
154  *     {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
155  * </ul>
156  *
157  * <p>
158  * This strategy works due to close cooperation with the target ClassLoader, as the entire code generation and loading
159  * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
160  */
161 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
162     // Not reusable definition: we can inline NodeContextSuppliers without a problem
163     // FIXME: 6.0.0: wire this implementation, which requires that BindingRuntimeTypes provides information about types
164     //               being generated from within a grouping
165     private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
166             implements NodeContextSupplierProvider<T> {
167         private final ImmutableMap<Method, NodeContextSupplier> properties;
168
169         Fixed(final TypeDescription superClass, final ImmutableMap<Method, NodeContextSupplier> properties,
170                 final @Nullable Method keyMethod) {
171             super(superClass, keyMethod);
172             this.properties = requireNonNull(properties);
173         }
174
175         @Override
176         Builder<T> generateGetters(final Builder<T> builder) {
177             Builder<T> tmp = builder;
178             for (Method method : properties.keySet()) {
179                 LOG.trace("Generating for fixed method {}", method);
180                 final String methodName = method.getName();
181                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
182                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
183                     new SupplierGetterMethodImplementation(methodName, retType));
184             }
185             return tmp;
186         }
187
188         @Override
189         ArrayList<Method> getterMethods() {
190             return new ArrayList<>(properties.keySet());
191         }
192
193         @Override
194         public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
195             final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
196                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
197             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
198             return verifyNotNull(found.get().getValue());
199         }
200     }
201
202     // Reusable definition: we have to rely on context lookups
203     private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
204             implements LocalNameProvider<T> {
205         private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
206         private final Map<Method, Class<?>> daoProperties;
207
208         Reusable(final TypeDescription superClass, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
209                 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
210             super(superClass, keyMethod);
211             this.simpleProperties = requireNonNull(simpleProperties);
212             this.daoProperties = requireNonNull(daoProperties);
213         }
214
215         @Override
216         Builder<T> generateGetters(final Builder<T> builder) {
217             Builder<T> tmp = builder;
218             for (Method method : simpleProperties.keySet()) {
219                 LOG.trace("Generating for simple method {}", method);
220                 final String methodName = method.getName();
221                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
222                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
223                     new SimpleGetterMethodImplementation(methodName, retType));
224             }
225             for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
226                 final Method method = entry.getKey();
227                 LOG.trace("Generating for structured method {}", method);
228                 final String methodName = method.getName();
229                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
230                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
231                     new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
232             }
233
234             return tmp;
235         }
236
237         @Override
238         ArrayList<Method> getterMethods() {
239             final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
240             ret.addAll(simpleProperties.keySet());
241             ret.addAll(daoProperties.keySet());
242             return ret;
243         }
244
245         @Override
246         public String resolveLocalName(final String methodName) {
247             final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
248                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
249             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
250             return found.get().getValue().getSchema().getQName().getLocalName();
251         }
252     }
253
254     private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
255     private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
256     private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
257     private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
258     private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
259     private static final TypeDescription BB_CDO = ForLoadedType.of(CodecDataObject.class);
260     private static final TypeDescription BB_ACDO = ForLoadedType.of(AugmentableCodecDataObject.class);
261     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
262
263     private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
264         byte[].class, byte[].class);
265     private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
266         Object.class, Object.class);
267     private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
268
269     private static final int PROT_FINAL = Opcodes.ACC_PROTECTED | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
270     private static final int PUB_FINAL = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
271
272     private static final ByteBuddy BB = new ByteBuddy();
273
274     private final TypeDescription superClass;
275     private final Method keyMethod;
276
277     CodecDataObjectGenerator(final TypeDescription superClass, final @Nullable Method keyMethod) {
278         this.superClass = requireNonNull(superClass);
279         this.keyMethod = keyMethod;
280     }
281
282     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
283             final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
284             final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
285         return loader.generateClass(bindingInterface, "codecImpl",
286             new Reusable<>(BB_CDO, simpleProperties, daoProperties, keyMethod));
287     }
288
289     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
290             final CodecClassLoader loader, final Class<D> bindingInterface,
291             final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
292             final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
293         return loader.generateClass(bindingInterface, "codecImpl",
294             new Reusable<>(BB_ACDO, simpleProperties, daoProperties, keyMethod));
295     }
296
297     @Override
298     public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
299             final Class<?> bindingInterface) {
300         LOG.trace("Generating class {}", fqcn);
301
302         final Generic bindingDef = TypeDefinition.Sort.describe(bindingInterface);
303         @SuppressWarnings("unchecked")
304         Builder<T> builder = (Builder<T>) BB.subclass(Generic.Builder.parameterizedType(superClass, bindingDef).build())
305             .visit(ByteBuddyUtils.computeFrames()).name(fqcn).implement(bindingDef);
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(codecHashCode(bindingInterface))
331                 // ... codecEquals() ...
332                 .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
333                 .intercept(codecEquals(methods))
334                 // ... toString() ...
335                 .defineMethod("toString", BB_STRING, PUB_FINAL)
336                 .intercept(toString(bindingInterface))
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 codecHashCode(final Class<?> bindingInterface) {
376         return new Implementation.Simple(
377             // return Foo.bindingHashCode(this);
378             THIS,
379             invokeMethod(bindingInterface, BindingMapping.BINDING_HASHCODE_NAME, bindingInterface),
380             MethodReturn.INTEGER);
381     }
382
383     private static Implementation toString(final Class<?> bindingInterface) {
384         return new Implementation.Simple(
385             // return Foo.bindingToString(this);
386             THIS,
387             invokeMethod(bindingInterface, BindingMapping.BINDING_TO_STRING_NAME, bindingInterface),
388             MethodReturn.REFERENCE);
389     }
390
391     private abstract static class AbstractMethodImplementation implements Implementation {
392         private static final Generic BB_HANDLE = TypeDefinition.Sort.describe(VarHandle.class);
393         private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
394         private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
395         private static final StackManipulation LOOKUP = invokeMethod(MethodHandles.class, "lookup");
396         private static final StackManipulation FIND_VAR_HANDLE = invokeMethod(Lookup.class,
397             "findVarHandle", Class.class, String.class, Class.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$$$V
407         final String handleName;
408
409         AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
410             this.methodName = requireNonNull(methodName);
411             this.retType = requireNonNull(retType);
412             this.handleName = methodName + "$$$V";
413         }
414
415         @Override
416         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
417             final InstrumentedType tmp = instrumentedType
418                     // private static final VarHandle getFoo$$$V;
419                     .withField(new FieldDescription.Token(handleName, PRIV_CONST, BB_HANDLE))
420                     // private volatile Object getFoo;
421                     .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
422
423             return tmp.withInitializer(new ByteCodeAppender.Simple(
424                 // TODO: acquiring lookup is expensive, we should share it across all initialization
425                 // getFoo$$$V = MethodHandles.lookup().findVarHandle(This.class, "getFoo", Object.class);
426                 LOOKUP,
427                 ClassConstant.of(tmp),
428                 new TextConstant(methodName),
429                 OBJECT_CLASS,
430                 FIND_VAR_HANDLE,
431                 putField(tmp, handleName)));
432         }
433     }
434
435     private static final class KeyMethodImplementation extends AbstractMethodImplementation {
436         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
437             "codecKey", VarHandle.class);
438
439         KeyMethodImplementation(final String methodName, final TypeDescription retType) {
440             super(methodName, retType);
441         }
442
443         @Override
444         public ByteCodeAppender appender(final Target implementationTarget) {
445             return new ByteCodeAppender.Simple(
446                 // return (FooType) codecKey(getFoo$$$V);
447                 THIS,
448                 getField(implementationTarget.getInstrumentedType(), handleName),
449                 CODEC_KEY,
450                 TypeCasting.to(retType),
451                 MethodReturn.REFERENCE);
452         }
453     }
454
455     /*
456      * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
457      * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
458      * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
459      * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
460      * on the constant pool entry to resolve to the same object.
461      */
462     private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
463         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
464             "codecMember", VarHandle.class, String.class);
465         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
466             "resolveLocalName", String.class);
467         private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
468
469         // getFoo$$$S
470         private final String stringName;
471
472         SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
473             super(methodName, retType);
474             this.stringName = methodName + "$$$S";
475         }
476
477         @Override
478         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
479             final InstrumentedType tmp = super.prepare(instrumentedType)
480                     // private static final String getFoo$$$S;
481                     .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
482
483             return tmp.withInitializer(new ByteCodeAppender.Simple(
484                 // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
485                 new TextConstant(methodName),
486                 BRIDGE_RESOLVE,
487                 putField(tmp, stringName)));
488         }
489
490         @Override
491         public ByteCodeAppender appender(final Target implementationTarget) {
492             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
493             return new ByteCodeAppender.Simple(
494                 // return (FooType) codecMember(getFoo$$$V, getFoo$$$S);
495                 THIS,
496                 getField(instrumentedType, handleName),
497                 getField(instrumentedType, stringName),
498                 CODEC_MEMBER,
499                 TypeCasting.to(retType),
500                 MethodReturn.REFERENCE);
501         }
502     }
503
504     private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
505         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
506             "codecMember", VarHandle.class, Class.class);
507
508         private final Class<?> bindingClass;
509
510         StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
511                 final Class<?> bindingClass) {
512             super(methodName, retType);
513             this.bindingClass = requireNonNull(bindingClass);
514         }
515
516         @Override
517         public ByteCodeAppender appender(final Target implementationTarget) {
518             return new ByteCodeAppender.Simple(
519                 // return (FooType) codecMember(getFoo$$$V, FooType.class);
520                 THIS,
521                 getField(implementationTarget.getInstrumentedType(), handleName),
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", VarHandle.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$$$V, getFoo$$$C);
562                 THIS,
563                 getField(instrumentedType, handleName),
564                 getField(instrumentedType, contextName),
565                 CODEC_MEMBER,
566                 TypeCasting.to(retType),
567                 MethodReturn.REFERENCE);
568         }
569     }
570 }