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