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