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