2 * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
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;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Maps;
21 import java.lang.reflect.Method;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Comparator;
25 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Objects;
29 import java.util.Optional;
30 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
31 import net.bytebuddy.ByteBuddy;
32 import net.bytebuddy.description.field.FieldDescription;
33 import net.bytebuddy.description.method.MethodDescription;
34 import net.bytebuddy.description.type.TypeDefinition;
35 import net.bytebuddy.description.type.TypeDescription;
36 import net.bytebuddy.description.type.TypeDescription.Generic;
37 import net.bytebuddy.dynamic.DynamicType.Builder;
38 import net.bytebuddy.dynamic.scaffold.InstrumentedType;
39 import net.bytebuddy.implementation.Implementation;
40 import net.bytebuddy.implementation.Implementation.Context;
41 import net.bytebuddy.implementation.bytecode.Addition;
42 import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
43 import net.bytebuddy.implementation.bytecode.Multiplication;
44 import net.bytebuddy.implementation.bytecode.StackManipulation;
45 import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
46 import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
47 import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
48 import net.bytebuddy.implementation.bytecode.constant.TextConstant;
49 import net.bytebuddy.implementation.bytecode.member.MethodReturn;
50 import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
51 import net.bytebuddy.jar.asm.Label;
52 import net.bytebuddy.jar.asm.MethodVisitor;
53 import net.bytebuddy.jar.asm.Opcodes;
54 import org.eclipse.jdt.annotation.Nullable;
55 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
56 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
57 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
58 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
59 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
60 import org.opendaylight.yangtools.yang.binding.DataObject;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
65 * Private support for generating {@link CodecDataObject} and {@link AugmentableCodecDataObject} specializations.
68 * Code generation here is probably more involved than usual mainly due to the fact we *really* want to express the
69 * strong connection between a generated class and BindingCodecContext in terms of a true constant, which boils down to
70 * {@code private static final NodeContextSupplier NCS}. Having such constants provides significant boost to JITs
71 * ability to optimize code -- especially with inlining and constant propagation.
74 * The accessor mapping performance is critical due to users typically not taking care of storing the results acquired
75 * by an invocation, assuming the accessors are backed by a normal field -- which of course is not true, as the results
76 * are lazily computed.
79 * The design is such that for a particular structure like:
87 * we end up generating a class with the following layout:
89 * public final class Foo$$$codecImpl extends CodecDataObject implements Foo {
90 * private static final AtomicRefereceFieldUpdater<Foo$$$codecImpl, Object> getBar$$$A;
91 * private volatile Object getBar;
93 * public Foo$$$codecImpl(NormalizedNodeContainer data) {
97 * public Bar getBar() {
98 * return (Bar) codecMember(getBar$$$A, "bar");
104 * This strategy minimizes the bytecode footprint and follows the generally good idea of keeping common logic in a
105 * single place in a maintainable form. The glue code is extremely light (~6 instructions), which is beneficial on both
106 * sides of invocation:
107 * - generated method can readily be inlined into the caller
108 * - it forms a call site into which codeMember() can be inlined with AtomicReferenceFieldUpdater being constant
111 * The second point is important here, as it allows the invocation logic around AtomicRefereceFieldUpdater to completely
112 * disappear, becoming synonymous with operations of a volatile field.
115 * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
117 * <li>with {@code String}, which ends up looking up a {@link ValueNodeCodecContext}</li>
118 * <li>with {@code Class}, which ends up looking up a {@link DataContainerCodecContext}</li>
119 * <li>with {@code NodeContextSupplier}, which performs a direct load</li>
121 * The third mode of operation requires that the object being implemented is not defined in a {@code grouping}, because
122 * it welds the object to a particular namespace -- hence it trades namespace mobility for access speed.
125 * The sticky point here is the NodeContextSupplier, as it is a heap object which cannot normally be looked up from the
126 * static context in which the static class initializer operates -- so we need perform some sort of a trick here.
127 * Eventhough ByteBuddy provides facilities for bridging references to type fields, those facilities operate on volatile
128 * fields -- hence they do not quite work for us.
131 * Another alternative, which we used in Javassist-generated DataObjectSerializers, is to muck with the static field
132 * using reflection -- which works, but requires redefinition of Field.modifiers, which is something Java 9 complains
133 * about quite noisily.
136 * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
137 * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
139 * <li>During code generation, the context fields are pointed towards
140 * {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
141 * {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
142 * in the context of a class initializer.</li>
143 * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
144 * class loading operation. At this point the generator installs itself as the current generator for this thread via
145 * {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
146 * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
147 * point the static invocations will be redirect to {@link #resolveNodeContextSupplier(String)} and
148 * {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
149 * <li>Before returning from the class loading call, the generator will detach itself via
150 * {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
154 * This strategy works due to close cooperation with the target ClassLoader, as the entire code generation and loading
155 * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
157 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
158 // Not reusable defintion: we can inline NodeContextSuppliers without a problem
159 private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
160 implements NodeContextSupplierProvider<T> {
161 private final ImmutableMap<Method, NodeContextSupplier> properties;
163 Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
164 final @Nullable Method keyMethod) {
165 super(template, keyMethod);
166 this.properties = requireNonNull(properties);
170 Builder<T> generateGetters(final Builder<T> builder) {
171 Builder<T> tmp = builder;
172 for (Method method : properties.keySet()) {
173 LOG.trace("Generating for fixed method {}", method);
174 final String methodName = method.getName();
175 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
176 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
177 new SupplierGetterMethodImplementation(methodName, retType));
183 ArrayList<Method> getterMethods() {
184 return new ArrayList<>(properties.keySet());
188 public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
189 final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
190 .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
191 verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
192 return verifyNotNull(found.get().getValue());
196 // Reusable definition: we have to rely on context lookups
197 private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
198 implements LocalNameProvider<T> {
199 private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
200 private final Map<Method, Class<?>> daoProperties;
202 Reusable(final Builder<?> template, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
203 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
204 super(template, keyMethod);
205 this.simpleProperties = requireNonNull(simpleProperties);
206 this.daoProperties = requireNonNull(daoProperties);
210 Builder<T> generateGetters(final Builder<T> builder) {
211 Builder<T> tmp = builder;
212 for (Method method : simpleProperties.keySet()) {
213 LOG.trace("Generating for simple method {}", method);
214 final String methodName = method.getName();
215 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
216 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
217 new SimpleGetterMethodImplementation(methodName, retType));
219 for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
220 final Method method = entry.getKey();
221 LOG.trace("Generating for structured method {}", method);
222 final String methodName = method.getName();
223 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
224 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
225 new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
232 ArrayList<Method> getterMethods() {
233 final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
234 ret.addAll(simpleProperties.keySet());
235 ret.addAll(daoProperties.keySet());
240 public String resolveLocalName(final String methodName) {
241 final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
242 .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
243 verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
244 return found.get().getValue().getSchema().getQName().getLocalName();
248 private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
249 private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
250 private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
251 private static final Generic BB_HELPER = TypeDefinition.Sort.describe(ToStringHelper.class);
252 private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
253 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
255 private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
256 byte[].class, byte[].class);
257 private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
258 Object.class, Object.class);
259 private static final StackManipulation HELPER_ADD = invokeMethod(ToStringHelper.class, "add",
260 String.class, Object.class);
262 private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
264 private static final int PROT_FINAL = Opcodes.ACC_PROTECTED | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
265 private static final int PUB_FINAL = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
267 private static final Builder<?> CDO;
268 private static final Builder<?> ACDO;
271 final ByteBuddy bb = new ByteBuddy();
272 CDO = bb.subclass(CodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
273 ACDO = bb.subclass(AugmentableCodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
276 private final Builder<?> template;
277 private final Method keyMethod;
279 private CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
280 this.template = requireNonNull(template);
281 this.keyMethod = keyMethod;
284 static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
285 final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
286 final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
287 return loader.generateClass(bindingInterface, "codecImpl",
288 new Reusable<>(CDO, simpleProperties, daoProperties, keyMethod));
291 static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
292 final CodecClassLoader loader, final Class<D> bindingInterface,
293 final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
294 final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
295 return loader.generateClass(bindingInterface, "codecImpl",
296 new Reusable<>(ACDO, simpleProperties, daoProperties, keyMethod));
300 public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
301 final Class<?> bindingInterface) {
302 LOG.trace("Generating class {}", fqcn);
304 @SuppressWarnings("unchecked")
305 Builder<T> builder = (Builder<T>) template.name(fqcn).implement(bindingInterface);
307 builder = generateGetters(builder);
309 if (keyMethod != null) {
310 LOG.trace("Generating for key {}", keyMethod);
311 final String methodName = keyMethod.getName();
312 final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
313 builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
314 new KeyMethodImplementation(methodName, retType));
317 // Index all property methods, turning them into "getFoo()" invocations, retaining order. We will be using
318 // those invocations in each of the three methods. Note that we do not glue the invocations to 'this', as we
319 // will be invoking them on 'other' in codecEquals()
320 final ArrayList<Method> properties = getterMethods();
321 // Make sure properties are alpha-sorted
322 properties.sort(METHOD_BY_ALPHABET);
323 final ImmutableMap<StackManipulation, Method> methods = Maps.uniqueIndex(properties,
324 ByteBuddyUtils::invokeMethod);
327 return GeneratorResult.of(builder
328 // codecHashCode() ...
329 .defineMethod("codecHashCode", BB_INT, PROT_FINAL)
330 .intercept(new Implementation.Simple(new CodecHashCode(methods)))
331 // ... codecEquals() ...
332 .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
333 .intercept(codecEquals(methods))
334 // ... and codecFillToString() ...
335 .defineMethod("codecFillToString", BB_HELPER, PROT_FINAL).withParameter(BB_HELPER)
336 .intercept(codecFillToString(methods))
341 abstract Builder<T> generateGetters(Builder<T> builder);
343 abstract ArrayList<Method> getterMethods();
345 private static Implementation codecEquals(final ImmutableMap<StackManipulation, Method> properties) {
346 // Label for 'return false;'
347 final Label falseLabel = new Label();
348 // Condition for 'if (!...)'
349 final StackManipulation ifFalse = ByteBuddyUtils.ifEq(falseLabel);
351 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 6 + 5);
352 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
353 // if (!java.util.(Objects|Arrays).equals(getFoo(), other.getFoo())) {
356 manipulations.add(THIS);
357 manipulations.add(entry.getKey());
358 manipulations.add(FIRST_ARG_REF);
359 manipulations.add(entry.getKey());
360 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_EQUALS : OBJECTS_EQUALS);
361 manipulations.add(ifFalse);
365 manipulations.add(IntegerConstant.ONE);
366 manipulations.add(MethodReturn.INTEGER);
368 manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
369 manipulations.add(IntegerConstant.ZERO);
370 manipulations.add(MethodReturn.INTEGER);
372 return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
375 private static Implementation codecFillToString(final ImmutableMap<StackManipulation, Method> properties) {
376 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 4 + 2);
377 // push 'return helper' to stack...
378 manipulations.add(FIRST_ARG_REF);
379 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
380 // .add("getFoo", getFoo())
381 manipulations.add(new TextConstant(entry.getValue().getName()));
382 manipulations.add(THIS);
383 manipulations.add(entry.getKey());
384 manipulations.add(HELPER_ADD);
386 // ... execute 'return helper'
387 manipulations.add(MethodReturn.REFERENCE);
389 return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
392 private abstract static class AbstractMethodImplementation implements Implementation {
393 private static final Generic BB_ARFU = TypeDefinition.Sort.describe(AtomicReferenceFieldUpdater.class);
394 private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
395 private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
396 private static final StackManipulation ARFU_NEWUPDATER = invokeMethod(AtomicReferenceFieldUpdater.class,
397 "newUpdater", Class.class, Class.class, String.class);
399 static final int PRIV_CONST = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
400 | Opcodes.ACC_SYNTHETIC;
401 private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
403 final TypeDescription retType;
405 final String methodName;
407 final String arfuName;
409 AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
410 this.methodName = requireNonNull(methodName);
411 this.retType = requireNonNull(retType);
412 this.arfuName = methodName + "$$$A";
416 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
417 final InstrumentedType tmp = instrumentedType
418 // private static final AtomicReferenceFieldUpdater<This, Object> getFoo$$$A;
419 .withField(new FieldDescription.Token(arfuName, PRIV_CONST, BB_ARFU))
420 // private volatile Object getFoo;
421 .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
423 return tmp.withInitializer(new ByteCodeAppender.Simple(
424 // getFoo$$$A = AtomicReferenceFieldUpdater.newUpdater(This.class, Object.class, "getFoo");
425 ClassConstant.of(tmp),
427 new TextConstant(methodName),
429 putField(tmp, arfuName)));
433 private static final class KeyMethodImplementation extends AbstractMethodImplementation {
434 private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
435 "codecKey", AtomicReferenceFieldUpdater.class);
437 KeyMethodImplementation(final String methodName, final TypeDescription retType) {
438 super(methodName, retType);
442 public ByteCodeAppender appender(final Target implementationTarget) {
443 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
444 return new ByteCodeAppender.Simple(
445 // return (FooType) codecKey(getFoo$$$A);
447 getField(instrumentedType, arfuName),
449 TypeCasting.to(retType),
450 MethodReturn.REFERENCE);
455 * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
456 * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
457 * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
458 * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
459 * on the constant pool entry to resolve to the same object.
461 private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
462 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
463 "codecMember", AtomicReferenceFieldUpdater.class, String.class);
464 private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
465 "resolveLocalName", String.class);
466 private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
469 private final String stringName;
471 SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
472 super(methodName, retType);
473 this.stringName = methodName + "$$$S";
477 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
478 final InstrumentedType tmp = super.prepare(instrumentedType)
479 // private static final String getFoo$$$S;
480 .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
482 return tmp.withInitializer(new ByteCodeAppender.Simple(
483 // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
484 new TextConstant(methodName),
486 putField(tmp, stringName)));
490 public ByteCodeAppender appender(final Target implementationTarget) {
491 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
492 return new ByteCodeAppender.Simple(
493 // return (FooType) codecMember(getFoo$$$A, getFoo$$$S);
495 getField(instrumentedType, arfuName),
496 getField(instrumentedType, stringName),
498 TypeCasting.to(retType),
499 MethodReturn.REFERENCE);
503 private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
504 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
505 "codecMember", AtomicReferenceFieldUpdater.class, Class.class);
507 private final Class<?> bindingClass;
509 StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
510 final Class<?> bindingClass) {
511 super(methodName, retType);
512 this.bindingClass = requireNonNull(bindingClass);
516 public ByteCodeAppender appender(final Target implementationTarget) {
517 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
518 return new ByteCodeAppender.Simple(
519 // return (FooType) codecMember(getFoo$$$A, FooType.class);
521 getField(instrumentedType, arfuName),
522 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
524 TypeCasting.to(retType),
525 MethodReturn.REFERENCE);
529 private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
530 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
531 "codecMember", AtomicReferenceFieldUpdater.class, NodeContextSupplier.class);
532 private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
533 "resolveNodeContextSupplier", String.class);
534 private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
537 private final String contextName;
539 SupplierGetterMethodImplementation(final String methodName, final TypeDescription retType) {
540 super(methodName, retType);
541 contextName = methodName + "$$$C";
545 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
546 final InstrumentedType tmp = super.prepare(instrumentedType)
547 // private static final NodeContextSupplier getFoo$$$C;
548 .withField(new FieldDescription.Token(contextName, PRIV_CONST, BB_NCS));
550 return tmp.withInitializer(new ByteCodeAppender.Simple(
551 // getFoo$$$C = CodecDataObjectBridge.resolve("getFoo");
552 new TextConstant(methodName),
554 putField(tmp, contextName)));
558 public ByteCodeAppender appender(final Target implementationTarget) {
559 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
560 return new ByteCodeAppender.Simple(
561 // return (FooType) codecMember(getFoo$$$A, getFoo$$$C);
563 getField(instrumentedType, arfuName),
564 getField(instrumentedType, contextName),
566 TypeCasting.to(retType),
567 MethodReturn.REFERENCE);
571 private static final class CodecHashCode implements ByteCodeAppender {
572 private static final StackManipulation THIRTY_ONE = IntegerConstant.forValue(31);
573 private static final StackManipulation LOAD_RESULT = MethodVariableAccess.INTEGER.loadFrom(1);
574 private static final StackManipulation STORE_RESULT = MethodVariableAccess.INTEGER.storeAt(1);
575 private static final StackManipulation ARRAYS_HASHCODE = invokeMethod(Arrays.class, "hashCode", byte[].class);
576 private static final StackManipulation OBJECTS_HASHCODE = invokeMethod(Objects.class, "hashCode", Object.class);
578 private final ImmutableMap<StackManipulation, Method> properties;
580 CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
581 this.properties = requireNonNull(properties);
585 public Size apply(final MethodVisitor methodVisitor, final Context implementationContext,
586 final MethodDescription instrumentedMethod) {
587 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 8 + 4);
589 manipulations.add(IntegerConstant.ONE);
590 manipulations.add(STORE_RESULT);
592 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
593 // result = 31 * result + java.util.(Objects,Arrays).hashCode(getFoo());
594 manipulations.add(THIRTY_ONE);
595 manipulations.add(LOAD_RESULT);
596 manipulations.add(Multiplication.INTEGER);
597 manipulations.add(THIS);
598 manipulations.add(entry.getKey());
599 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_HASHCODE : OBJECTS_HASHCODE);
600 manipulations.add(Addition.INTEGER);
601 manipulations.add(STORE_RESULT);
604 manipulations.add(LOAD_RESULT);
605 manipulations.add(MethodReturn.INTEGER);
607 StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
608 .apply(methodVisitor, implementationContext);
609 return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);