Hide CodecDataObjectGenerator subclasses
[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     private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
163             implements NodeContextSupplierProvider {
164         private final ImmutableMap<Method, NodeContextSupplier> properties;
165
166         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     private 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         Reusable(final Builder<?> template, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
206                 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
207             super(template, keyMethod);
208             this.simpleProperties = requireNonNull(simpleProperties);
209             this.daoProperties = requireNonNull(daoProperties);
210         }
211
212         @Override
213         Builder<T> generateGetters(final Builder<T> builder) {
214             Builder<T> tmp = builder;
215             for (Method method : simpleProperties.keySet()) {
216                 LOG.trace("Generating for simple method {}", method);
217                 final String methodName = method.getName();
218                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
219                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
220                     new SimpleGetterMethodImplementation(methodName, retType));
221             }
222             for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
223                 final Method method = entry.getKey();
224                 LOG.trace("Generating for structured method {}", method);
225                 final String methodName = method.getName();
226                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
227                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
228                     new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
229             }
230
231             return tmp;
232         }
233
234         @Override
235         ArrayList<Method> getterMethods() {
236             final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
237             ret.addAll(simpleProperties.keySet());
238             ret.addAll(daoProperties.keySet());
239             return ret;
240         }
241
242         @Override
243         public String resolveLocalName(final String methodName) {
244             final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
245                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
246             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
247             return found.get().getValue().getSchema().getQName().getLocalName();
248         }
249     }
250
251     private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
252     private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
253     private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
254     private static final Generic BB_HELPER = TypeDefinition.Sort.describe(ToStringHelper.class);
255     private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
256     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
257
258     private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
259         byte[].class, byte[].class);
260     private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
261         Object.class, Object.class);
262     private static final StackManipulation HELPER_ADD = invokeMethod(ToStringHelper.class, "add",
263         String.class, Object.class);
264
265     private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
266
267     private static final int PROT_FINAL = Opcodes.ACC_PROTECTED | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
268     private static final int PUB_FINAL = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
269
270     private static final Builder<?> CDO;
271     private static final Builder<?> ACDO;
272
273     static {
274         final ByteBuddy bb = new ByteBuddy();
275         CDO = bb.subclass(CodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
276         ACDO = bb.subclass(AugmentableCodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
277     }
278
279     private final Builder<?> template;
280     private final Method keyMethod;
281
282     private CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
283         this.template = requireNonNull(template);
284         this.keyMethod = keyMethod;
285     }
286
287     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
288             final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
289             final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
290         return loader.generateClass(bindingInterface, "codecImpl",
291             new Reusable<>(CDO, simpleProperties, daoProperties, keyMethod));
292     }
293
294     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
295             final CodecClassLoader loader, final Class<D> bindingInterface,
296             final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
297             final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
298         return loader.generateClass(bindingInterface, "codecImpl",
299             new Reusable<>(ACDO, simpleProperties, daoProperties, keyMethod));
300     }
301
302     @Override
303     public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
304             final Class<?> bindingInterface) {
305         LOG.trace("Generating class {}", fqcn);
306
307         @SuppressWarnings("unchecked")
308         Builder<T> builder = (Builder<T>) template.name(fqcn).implement(bindingInterface);
309
310         builder = generateGetters(builder);
311
312         if (keyMethod != null) {
313             LOG.trace("Generating for key {}", keyMethod);
314             final String methodName = keyMethod.getName();
315             final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
316             builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
317                 new KeyMethodImplementation(methodName, retType));
318         }
319
320         // Index all property methods, turning them into "getFoo()" invocations, retaining order. We will be using
321         // those invocations in each of the three methods. Note that we do not glue the invocations to 'this', as we
322         // will be invoking them on 'other' in codecEquals()
323         final ArrayList<Method> properties = getterMethods();
324         // Make sure properties are alpha-sorted
325         properties.sort(METHOD_BY_ALPHABET);
326         final ImmutableMap<StackManipulation, Method> methods = Maps.uniqueIndex(properties,
327             ByteBuddyUtils::invokeMethod);
328
329         // Final bits:
330         return GeneratorResult.of(builder
331                 // codecHashCode() ...
332                 .defineMethod("codecHashCode", BB_INT, PROT_FINAL)
333                 .intercept(new Implementation.Simple(new CodecHashCode(methods)))
334                 // ... codecEquals() ...
335                 .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
336                 .intercept(codecEquals(methods))
337                 // ... and codecFillToString() ...
338                 .defineMethod("codecFillToString", BB_HELPER, PROT_FINAL).withParameter(BB_HELPER)
339                 .intercept(codecFillToString(methods))
340                 // ... and build it
341                 .make());
342     }
343
344     @Override
345     public Class<T> customizeLoading(final @NonNull Supplier<Class<T>> loader) {
346         final BridgeProvider prev = ClassGeneratorBridge.setup(this);
347         try {
348             final Class<T> result = loader.get();
349
350             /*
351              * This a bit of magic to support NodeContextSupplier constants. These constants need to be resolved
352              * while we have the information needed to find them -- that information is being held in this instance
353              * and we leak it to a thread-local variable held by CodecDataObjectBridge.
354              *
355              * By default the JVM will defer class initialization to first use, which unfortunately is too late for
356              * us, and hence we need to force class to initialize.
357              */
358             try {
359                 Class.forName(result.getName(), true, result.getClassLoader());
360             } catch (ClassNotFoundException e) {
361                 throw new LinkageError("Failed to find newly-defined " + result, e);
362             }
363
364             return result;
365         } finally {
366             ClassGeneratorBridge.tearDown(prev);
367         }
368     }
369
370     abstract Builder<T> generateGetters(Builder<T> builder);
371
372     abstract ArrayList<Method> getterMethods();
373
374     private static Implementation codecEquals(final ImmutableMap<StackManipulation, Method> properties) {
375         // Label for 'return false;'
376         final Label falseLabel = new Label();
377         // Condition for 'if (!...)'
378         final StackManipulation ifFalse = ByteBuddyUtils.ifEq(falseLabel);
379
380         final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 6 + 5);
381         for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
382             // if (!java.util.(Objects|Arrays).equals(getFoo(), other.getFoo())) {
383             //     return false;
384             // }
385             manipulations.add(THIS);
386             manipulations.add(entry.getKey());
387             manipulations.add(FIRST_ARG_REF);
388             manipulations.add(entry.getKey());
389             manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_EQUALS : OBJECTS_EQUALS);
390             manipulations.add(ifFalse);
391         }
392
393         // return true;
394         manipulations.add(IntegerConstant.ONE);
395         manipulations.add(MethodReturn.INTEGER);
396         // L0: return false;
397         manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
398         manipulations.add(IntegerConstant.ZERO);
399         manipulations.add(MethodReturn.INTEGER);
400
401         return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
402     }
403
404     private static Implementation codecFillToString(final ImmutableMap<StackManipulation, Method> properties) {
405         final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 4 + 2);
406         // push 'return helper' to stack...
407         manipulations.add(FIRST_ARG_REF);
408         for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
409             // .add("getFoo", getFoo())
410             manipulations.add(new TextConstant(entry.getValue().getName()));
411             manipulations.add(THIS);
412             manipulations.add(entry.getKey());
413             manipulations.add(HELPER_ADD);
414         }
415         // ... execute 'return helper'
416         manipulations.add(MethodReturn.REFERENCE);
417
418         return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
419     }
420
421     private abstract static class AbstractMethodImplementation implements Implementation {
422         private static final Generic BB_ARFU = TypeDefinition.Sort.describe(AtomicReferenceFieldUpdater.class);
423         private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
424         private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
425         private static final StackManipulation ARFU_NEWUPDATER = invokeMethod(AtomicReferenceFieldUpdater.class,
426             "newUpdater", Class.class, Class.class, String.class);
427
428         static final int PRIV_CONST = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
429                 | Opcodes.ACC_SYNTHETIC;
430         private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
431
432         final TypeDescription retType;
433         // getFoo
434         final String methodName;
435         // getFoo$$$A
436         final String arfuName;
437
438         AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
439             this.methodName = requireNonNull(methodName);
440             this.retType = requireNonNull(retType);
441             this.arfuName = methodName + "$$$A";
442         }
443
444         @Override
445         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
446             final InstrumentedType tmp = instrumentedType
447                     // private static final AtomicReferenceFieldUpdater<This, Object> getFoo$$$A;
448                     .withField(new FieldDescription.Token(arfuName, PRIV_CONST, BB_ARFU))
449                     // private volatile Object getFoo;
450                     .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
451
452             return tmp.withInitializer(new ByteCodeAppender.Simple(
453                 // getFoo$$$A = AtomicReferenceFieldUpdater.newUpdater(This.class, Object.class, "getFoo");
454                 ClassConstant.of(tmp),
455                 OBJECT_CLASS,
456                 new TextConstant(methodName),
457                 ARFU_NEWUPDATER,
458                 putField(tmp, arfuName)));
459         }
460     }
461
462     private static final class KeyMethodImplementation extends AbstractMethodImplementation {
463         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
464             "codecKey", AtomicReferenceFieldUpdater.class);
465
466         KeyMethodImplementation(final String methodName, final TypeDescription retType) {
467             super(methodName, retType);
468         }
469
470         @Override
471         public ByteCodeAppender appender(final Target implementationTarget) {
472             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
473             return new ByteCodeAppender.Simple(
474                 // return (FooType) codecKey(getFoo$$$A);
475                 THIS,
476                 getField(instrumentedType, arfuName),
477                 CODEC_KEY,
478                 TypeCasting.to(retType),
479                 MethodReturn.REFERENCE);
480         }
481     }
482
483     /*
484      * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
485      * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
486      * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
487      * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
488      * on the constant pool entry to resolve to the same object.
489      */
490     private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
491         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
492             "codecMember", AtomicReferenceFieldUpdater.class, String.class);
493         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
494             "resolveLocalName", String.class);
495         private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
496
497         // getFoo$$$S
498         private final String stringName;
499
500         SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
501             super(methodName, retType);
502             this.stringName = methodName + "$$$S";
503         }
504
505         @Override
506         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
507             final InstrumentedType tmp = super.prepare(instrumentedType)
508                     // private static final String getFoo$$$S;
509                     .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
510
511             return tmp.withInitializer(new ByteCodeAppender.Simple(
512                 // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
513                 new TextConstant(methodName),
514                 BRIDGE_RESOLVE,
515                 putField(tmp, stringName)));
516         }
517
518         @Override
519         public ByteCodeAppender appender(final Target implementationTarget) {
520             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
521             return new ByteCodeAppender.Simple(
522                 // return (FooType) codecMember(getFoo$$$A, getFoo$$$S);
523                 THIS,
524                 getField(instrumentedType, arfuName),
525                 getField(instrumentedType, stringName),
526                 CODEC_MEMBER,
527                 TypeCasting.to(retType),
528                 MethodReturn.REFERENCE);
529         }
530     }
531
532     private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
533         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
534             "codecMember", AtomicReferenceFieldUpdater.class, Class.class);
535
536         private final Class<?> bindingClass;
537
538         StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
539                 final Class<?> bindingClass) {
540             super(methodName, retType);
541             this.bindingClass = requireNonNull(bindingClass);
542         }
543
544         @Override
545         public ByteCodeAppender appender(final Target implementationTarget) {
546             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
547             return new ByteCodeAppender.Simple(
548                 // return (FooType) codecMember(getFoo$$$A, FooType.class);
549                 THIS,
550                 getField(instrumentedType, arfuName),
551                 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
552                 CODEC_MEMBER,
553                 TypeCasting.to(retType),
554                 MethodReturn.REFERENCE);
555         }
556     }
557
558     private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
559         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
560             "codecMember", AtomicReferenceFieldUpdater.class, NodeContextSupplier.class);
561         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
562             "resolveNodeContextSupplier", String.class);
563         private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
564
565         // getFoo$$$C
566         private final String contextName;
567
568         SupplierGetterMethodImplementation(final String methodName, final TypeDescription retType) {
569             super(methodName, retType);
570             contextName = methodName + "$$$C";
571         }
572
573         @Override
574         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
575             final InstrumentedType tmp = super.prepare(instrumentedType)
576                     // private static final NodeContextSupplier getFoo$$$C;
577                     .withField(new FieldDescription.Token(contextName, PRIV_CONST, BB_NCS));
578
579             return tmp.withInitializer(new ByteCodeAppender.Simple(
580                 // getFoo$$$C = CodecDataObjectBridge.resolve("getFoo");
581                 new TextConstant(methodName),
582                 BRIDGE_RESOLVE,
583                 putField(tmp, contextName)));
584         }
585
586         @Override
587         public ByteCodeAppender appender(final Target implementationTarget) {
588             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
589             return new ByteCodeAppender.Simple(
590                 // return (FooType) codecMember(getFoo$$$A, getFoo$$$C);
591                 THIS,
592                 getField(instrumentedType, arfuName),
593                 getField(instrumentedType, contextName),
594                 CODEC_MEMBER,
595                 TypeCasting.to(retType),
596                 MethodReturn.REFERENCE);
597         }
598     }
599
600     private static final class CodecHashCode implements ByteCodeAppender {
601         private static final StackManipulation THIRTY_ONE = IntegerConstant.forValue(31);
602         private static final StackManipulation LOAD_RESULT = MethodVariableAccess.INTEGER.loadFrom(1);
603         private static final StackManipulation STORE_RESULT = MethodVariableAccess.INTEGER.storeAt(1);
604         private static final StackManipulation ARRAYS_HASHCODE = invokeMethod(Arrays.class, "hashCode", byte[].class);
605         private static final StackManipulation OBJECTS_HASHCODE = invokeMethod(Objects.class, "hashCode", Object.class);
606
607         private final ImmutableMap<StackManipulation, Method> properties;
608
609         CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
610             this.properties = requireNonNull(properties);
611         }
612
613         @Override
614         public Size apply(final MethodVisitor methodVisitor, final Context implementationContext,
615                 final MethodDescription instrumentedMethod) {
616             final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 8 + 4);
617             // int result = 1;
618             manipulations.add(IntegerConstant.ONE);
619             manipulations.add(STORE_RESULT);
620
621             for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
622                 // result = 31 * result + java.util.(Objects,Arrays).hashCode(getFoo());
623                 manipulations.add(THIRTY_ONE);
624                 manipulations.add(LOAD_RESULT);
625                 manipulations.add(Multiplication.INTEGER);
626                 manipulations.add(THIS);
627                 manipulations.add(entry.getKey());
628                 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_HASHCODE : OBJECTS_HASHCODE);
629                 manipulations.add(Addition.INTEGER);
630                 manipulations.add(STORE_RESULT);
631             }
632             // return result;
633             manipulations.add(LOAD_RESULT);
634             manipulations.add(MethodReturn.INTEGER);
635
636             StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
637                     .apply(methodVisitor, implementationContext);
638             return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);
639         }
640     }
641 }