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.invoke.MethodHandles;
22 import java.lang.invoke.MethodHandles.Lookup;
23 import java.lang.invoke.VarHandle;
24 import java.lang.reflect.Method;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Comparator;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Objects;
32 import java.util.Optional;
33 import net.bytebuddy.ByteBuddy;
34 import net.bytebuddy.description.field.FieldDescription;
35 import net.bytebuddy.description.method.MethodDescription;
36 import net.bytebuddy.description.type.TypeDefinition;
37 import net.bytebuddy.description.type.TypeDescription;
38 import net.bytebuddy.description.type.TypeDescription.Generic;
39 import net.bytebuddy.dynamic.DynamicType.Builder;
40 import net.bytebuddy.dynamic.scaffold.InstrumentedType;
41 import net.bytebuddy.implementation.Implementation;
42 import net.bytebuddy.implementation.Implementation.Context;
43 import net.bytebuddy.implementation.bytecode.Addition;
44 import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
45 import net.bytebuddy.implementation.bytecode.Multiplication;
46 import net.bytebuddy.implementation.bytecode.StackManipulation;
47 import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
48 import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
49 import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
50 import net.bytebuddy.implementation.bytecode.constant.TextConstant;
51 import net.bytebuddy.implementation.bytecode.member.MethodReturn;
52 import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
53 import net.bytebuddy.jar.asm.Label;
54 import net.bytebuddy.jar.asm.MethodVisitor;
55 import net.bytebuddy.jar.asm.Opcodes;
56 import org.eclipse.jdt.annotation.Nullable;
57 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
58 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
59 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
60 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
61 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
62 import org.opendaylight.yangtools.yang.binding.DataObject;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
67 * Private support for generating {@link CodecDataObject} and {@link AugmentableCodecDataObject} specializations.
70 * Code generation here is probably more involved than usual mainly due to the fact we *really* want to express the
71 * strong connection between a generated class to the extent possible. In most cases (grouping-generated types) this
72 * involves one level of indirection, which is a safe approach. If we are dealing with a type generated outside of a
73 * grouping statement, though, we are guaranteed instantiation-invariance and hence can hard-wire to a runtime-constant
74 * {@link NodeContextSupplier} -- which provides significant boost to JITs ability to optimize code -- especially with
75 * inlining and constant propagation.
78 * The accessor mapping performance is critical due to users typically not taking care of storing the results acquired
79 * by an invocation, assuming the accessors are backed by a normal field -- which of course is not true, as the results
80 * are lazily computed.
83 * The design is such that for a particular structure like:
91 * we end up generating a class with the following layout:
93 * public final class Foo$$$codecImpl extends CodecDataObject implements Foo {
94 * private static final VarHandle getBar$$$V;
95 * private volatile Object getBar;
97 * public Foo$$$codecImpl(NormalizedNodeContainer data) {
101 * public Bar getBar() {
102 * return (Bar) codecMember(getBar$$$V, "bar");
108 * This strategy minimizes the bytecode footprint and follows the generally good idea of keeping common logic in a
109 * single place in a maintainable form. The glue code is extremely light (~6 instructions), which is beneficial on both
110 * sides of invocation:
112 * <li>generated method can readily be inlined into the caller</li>
113 * <li>it forms a call site into which codeMember() can be inlined with VarHandle being constant</li>
117 * The second point is important here, as it allows the invocation logic around VarHandle to completely disappear,
118 * becoming synonymous with operations on a field. Even though the field itself is declared as volatile, it is only ever
119 * accessed through helper method using VarHandles -- and those helpers are using relaxed field ordering
120 * of {@code getAcquire()}/{@code setRelease()} memory semantics.
123 * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
125 * <li>with {@code String}, which ends up looking up a {@link ValueNodeCodecContext}</li>
126 * <li>with {@code Class}, which ends up looking up a {@link DataContainerCodecContext}</li>
127 * <li>with {@code NodeContextSupplier}, which performs a direct load</li>
129 * The third mode of operation requires that the object being implemented is not defined in a {@code grouping}, because
130 * it welds the object to a particular namespace -- hence it trades namespace mobility for access speed.
133 * The sticky point here is the NodeContextSupplier, as it is a heap object which cannot normally be looked up from the
134 * static context in which the static class initializer operates -- so we need perform some sort of a trick here.
135 * Even though ByteBuddy provides facilities for bridging references to type fields, those facilities operate on
136 * volatile fields -- hence they do not quite work for us.
139 * Another alternative, which we used in Javassist-generated DataObjectSerializers, is to muck with the static field
140 * using reflection -- which works, but requires redefinition of Field.modifiers, which is something Java 9+ complains
141 * about quite noisily.
144 * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
145 * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
147 * <li>During code generation, the context fields are pointed towards
148 * {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
149 * {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
150 * in the context of a class initializer.</li>
151 * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
152 * class loading operation. At this point the generator installs itself as the current generator for this thread via
153 * {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
154 * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
155 * point the static invocations will be redirected to {@link #resolveNodeContextSupplier(String)} and
156 * {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
157 * <li>Before returning from the class loading call, the generator will detach itself via
158 * {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
162 * This strategy works due to close cooperation with the target ClassLoader, as the entire code generation and loading
163 * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
165 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
166 // Not reusable definition: we can inline NodeContextSuppliers without a problem
167 // FIXME: 6.0.0: wire this implementation, which requires that BindingRuntimeTypes provides information about types
168 // being generated from within a grouping
169 private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
170 implements NodeContextSupplierProvider<T> {
171 private final ImmutableMap<Method, NodeContextSupplier> properties;
173 Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
174 final @Nullable Method keyMethod) {
175 super(template, keyMethod);
176 this.properties = requireNonNull(properties);
180 Builder<T> generateGetters(final Builder<T> builder) {
181 Builder<T> tmp = builder;
182 for (Method method : properties.keySet()) {
183 LOG.trace("Generating for fixed method {}", method);
184 final String methodName = method.getName();
185 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
186 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
187 new SupplierGetterMethodImplementation(methodName, retType));
193 ArrayList<Method> getterMethods() {
194 return new ArrayList<>(properties.keySet());
198 public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
199 final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
200 .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
201 verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
202 return verifyNotNull(found.get().getValue());
206 // Reusable definition: we have to rely on context lookups
207 private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
208 implements LocalNameProvider<T> {
209 private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
210 private final Map<Method, Class<?>> daoProperties;
212 Reusable(final Builder<?> template, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
213 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
214 super(template, keyMethod);
215 this.simpleProperties = requireNonNull(simpleProperties);
216 this.daoProperties = requireNonNull(daoProperties);
220 Builder<T> generateGetters(final Builder<T> builder) {
221 Builder<T> tmp = builder;
222 for (Method method : simpleProperties.keySet()) {
223 LOG.trace("Generating for simple method {}", method);
224 final String methodName = method.getName();
225 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
226 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
227 new SimpleGetterMethodImplementation(methodName, retType));
229 for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
230 final Method method = entry.getKey();
231 LOG.trace("Generating for structured method {}", method);
232 final String methodName = method.getName();
233 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
234 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
235 new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
242 ArrayList<Method> getterMethods() {
243 final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
244 ret.addAll(simpleProperties.keySet());
245 ret.addAll(daoProperties.keySet());
250 public String resolveLocalName(final String methodName) {
251 final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
252 .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
253 verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
254 return found.get().getValue().getSchema().getQName().getLocalName();
258 private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
259 private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
260 private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
261 private static final Generic BB_HELPER = TypeDefinition.Sort.describe(ToStringHelper.class);
262 private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
263 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
265 private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
266 byte[].class, byte[].class);
267 private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
268 Object.class, Object.class);
269 private static final StackManipulation HELPER_ADD = invokeMethod(ToStringHelper.class, "add",
270 String.class, Object.class);
272 private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
274 private static final int PROT_FINAL = Opcodes.ACC_PROTECTED | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
275 private static final int PUB_FINAL = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
277 private static final Builder<?> CDO;
278 private static final Builder<?> ACDO;
281 final ByteBuddy bb = new ByteBuddy();
282 CDO = bb.subclass(CodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
283 ACDO = bb.subclass(AugmentableCodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
286 private final Builder<?> template;
287 private final Method keyMethod;
289 CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
290 this.template = requireNonNull(template);
291 this.keyMethod = keyMethod;
294 static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
295 final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
296 final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
297 return loader.generateClass(bindingInterface, "codecImpl",
298 new Reusable<>(CDO, simpleProperties, daoProperties, keyMethod));
301 static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
302 final CodecClassLoader loader, final Class<D> bindingInterface,
303 final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
304 final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
305 return loader.generateClass(bindingInterface, "codecImpl",
306 new Reusable<>(ACDO, simpleProperties, daoProperties, keyMethod));
310 public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
311 final Class<?> bindingInterface) {
312 LOG.trace("Generating class {}", fqcn);
314 @SuppressWarnings("unchecked")
315 Builder<T> builder = (Builder<T>) template.name(fqcn).implement(bindingInterface);
317 builder = generateGetters(builder);
319 if (keyMethod != null) {
320 LOG.trace("Generating for key {}", keyMethod);
321 final String methodName = keyMethod.getName();
322 final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
323 builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
324 new KeyMethodImplementation(methodName, retType));
327 // Index all property methods, turning them into "getFoo()" invocations, retaining order. We will be using
328 // those invocations in each of the three methods. Note that we do not glue the invocations to 'this', as we
329 // will be invoking them on 'other' in codecEquals()
330 final ArrayList<Method> properties = getterMethods();
331 // Make sure properties are alpha-sorted
332 properties.sort(METHOD_BY_ALPHABET);
333 final ImmutableMap<StackManipulation, Method> methods = Maps.uniqueIndex(properties,
334 ByteBuddyUtils::invokeMethod);
337 return GeneratorResult.of(builder
338 // codecHashCode() ...
339 .defineMethod("codecHashCode", BB_INT, PROT_FINAL)
340 .intercept(new Implementation.Simple(new CodecHashCode(methods)))
341 // ... codecEquals() ...
342 .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
343 .intercept(codecEquals(methods))
344 // ... and codecFillToString() ...
345 .defineMethod("codecFillToString", BB_HELPER, PROT_FINAL).withParameter(BB_HELPER)
346 .intercept(codecFillToString(methods))
351 abstract Builder<T> generateGetters(Builder<T> builder);
353 abstract ArrayList<Method> getterMethods();
355 private static Implementation codecEquals(final ImmutableMap<StackManipulation, Method> properties) {
356 // Label for 'return false;'
357 final Label falseLabel = new Label();
358 // Condition for 'if (!...)'
359 final StackManipulation ifFalse = ByteBuddyUtils.ifEq(falseLabel);
361 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 6 + 5);
362 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
363 // if (!java.util.(Objects|Arrays).equals(getFoo(), other.getFoo())) {
366 manipulations.add(THIS);
367 manipulations.add(entry.getKey());
368 manipulations.add(FIRST_ARG_REF);
369 manipulations.add(entry.getKey());
370 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_EQUALS : OBJECTS_EQUALS);
371 manipulations.add(ifFalse);
375 manipulations.add(IntegerConstant.ONE);
376 manipulations.add(MethodReturn.INTEGER);
378 manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
379 manipulations.add(IntegerConstant.ZERO);
380 manipulations.add(MethodReturn.INTEGER);
382 return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
385 private static Implementation codecFillToString(final ImmutableMap<StackManipulation, Method> properties) {
386 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 4 + 2);
387 // push 'return helper' to stack...
388 manipulations.add(FIRST_ARG_REF);
389 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
390 // .add("getFoo", getFoo())
391 manipulations.add(new TextConstant(entry.getValue().getName()));
392 manipulations.add(THIS);
393 manipulations.add(entry.getKey());
394 manipulations.add(HELPER_ADD);
396 // ... execute 'return helper'
397 manipulations.add(MethodReturn.REFERENCE);
399 return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
402 private abstract static class AbstractMethodImplementation implements Implementation {
403 private static final Generic BB_HANDLE = TypeDefinition.Sort.describe(VarHandle.class);
404 private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
405 private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
406 private static final StackManipulation LOOKUP = invokeMethod(MethodHandles.class, "lookup");
407 private static final StackManipulation FIND_VAR_HANDLE = invokeMethod(Lookup.class,
408 "findVarHandle", Class.class, String.class, Class.class);
410 static final int PRIV_CONST = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
411 | Opcodes.ACC_SYNTHETIC;
412 private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
414 final TypeDescription retType;
416 final String methodName;
418 final String handleName;
420 AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
421 this.methodName = requireNonNull(methodName);
422 this.retType = requireNonNull(retType);
423 this.handleName = methodName + "$$$V";
427 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
428 final InstrumentedType tmp = instrumentedType
429 // private static final VarHandle getFoo$$$V;
430 .withField(new FieldDescription.Token(handleName, PRIV_CONST, BB_HANDLE))
431 // private volatile Object getFoo;
432 .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
434 return tmp.withInitializer(new ByteCodeAppender.Simple(
435 // TODO: acquiring lookup is expensive, we should share it across all initialization
436 // getFoo$$$V = MethodHandles.lookup().findVarHandle(This.class, "getFoo", Object.class);
438 ClassConstant.of(tmp),
439 new TextConstant(methodName),
442 putField(tmp, handleName)));
446 private static final class KeyMethodImplementation extends AbstractMethodImplementation {
447 private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
448 "codecKey", VarHandle.class);
450 KeyMethodImplementation(final String methodName, final TypeDescription retType) {
451 super(methodName, retType);
455 public ByteCodeAppender appender(final Target implementationTarget) {
456 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
457 return new ByteCodeAppender.Simple(
458 // return (FooType) codecKey(getFoo$$$V);
460 getField(instrumentedType, handleName),
462 TypeCasting.to(retType),
463 MethodReturn.REFERENCE);
468 * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
469 * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
470 * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
471 * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
472 * on the constant pool entry to resolve to the same object.
474 private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
475 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
476 "codecMember", VarHandle.class, String.class);
477 private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
478 "resolveLocalName", String.class);
479 private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
482 private final String stringName;
484 SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
485 super(methodName, retType);
486 this.stringName = methodName + "$$$S";
490 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
491 final InstrumentedType tmp = super.prepare(instrumentedType)
492 // private static final String getFoo$$$S;
493 .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
495 return tmp.withInitializer(new ByteCodeAppender.Simple(
496 // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
497 new TextConstant(methodName),
499 putField(tmp, stringName)));
503 public ByteCodeAppender appender(final Target implementationTarget) {
504 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
505 return new ByteCodeAppender.Simple(
506 // return (FooType) codecMember(getFoo$$$V, getFoo$$$S);
508 getField(instrumentedType, handleName),
509 getField(instrumentedType, stringName),
511 TypeCasting.to(retType),
512 MethodReturn.REFERENCE);
516 private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
517 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
518 "codecMember", VarHandle.class, Class.class);
520 private final Class<?> bindingClass;
522 StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
523 final Class<?> bindingClass) {
524 super(methodName, retType);
525 this.bindingClass = requireNonNull(bindingClass);
529 public ByteCodeAppender appender(final Target implementationTarget) {
530 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
531 return new ByteCodeAppender.Simple(
532 // return (FooType) codecMember(getFoo$$$V, FooType.class);
534 getField(instrumentedType, handleName),
535 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
537 TypeCasting.to(retType),
538 MethodReturn.REFERENCE);
542 private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
543 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
544 "codecMember", VarHandle.class, NodeContextSupplier.class);
545 private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
546 "resolveNodeContextSupplier", String.class);
547 private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
550 private final String contextName;
552 SupplierGetterMethodImplementation(final String methodName, final TypeDescription retType) {
553 super(methodName, retType);
554 contextName = methodName + "$$$C";
558 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
559 final InstrumentedType tmp = super.prepare(instrumentedType)
560 // private static final NodeContextSupplier getFoo$$$C;
561 .withField(new FieldDescription.Token(contextName, PRIV_CONST, BB_NCS));
563 return tmp.withInitializer(new ByteCodeAppender.Simple(
564 // getFoo$$$C = CodecDataObjectBridge.resolve("getFoo");
565 new TextConstant(methodName),
567 putField(tmp, contextName)));
571 public ByteCodeAppender appender(final Target implementationTarget) {
572 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
573 return new ByteCodeAppender.Simple(
574 // return (FooType) codecMember(getFoo$$$V, getFoo$$$C);
576 getField(instrumentedType, handleName),
577 getField(instrumentedType, contextName),
579 TypeCasting.to(retType),
580 MethodReturn.REFERENCE);
584 private static final class CodecHashCode implements ByteCodeAppender {
585 private static final StackManipulation THIRTY_ONE = IntegerConstant.forValue(31);
586 private static final StackManipulation LOAD_RESULT = MethodVariableAccess.INTEGER.loadFrom(1);
587 private static final StackManipulation STORE_RESULT = MethodVariableAccess.INTEGER.storeAt(1);
588 private static final StackManipulation ARRAYS_HASHCODE = invokeMethod(Arrays.class, "hashCode", byte[].class);
589 private static final StackManipulation OBJECTS_HASHCODE = invokeMethod(Objects.class, "hashCode", Object.class);
591 private final ImmutableMap<StackManipulation, Method> properties;
593 CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
594 this.properties = requireNonNull(properties);
598 public Size apply(final MethodVisitor methodVisitor, final Context implementationContext,
599 final MethodDescription instrumentedMethod) {
600 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 8 + 4);
602 manipulations.add(IntegerConstant.ONE);
603 manipulations.add(STORE_RESULT);
605 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
606 // result = 31 * result + java.util.(Objects,Arrays).hashCode(getFoo());
607 manipulations.add(THIRTY_ONE);
608 manipulations.add(LOAD_RESULT);
609 manipulations.add(Multiplication.INTEGER);
610 manipulations.add(THIS);
611 manipulations.add(entry.getKey());
612 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_HASHCODE : OBJECTS_HASHCODE);
613 manipulations.add(Addition.INTEGER);
614 manipulations.add(STORE_RESULT);
617 manipulations.add(LOAD_RESULT);
618 manipulations.add(MethodReturn.INTEGER);
620 StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
621 .apply(methodVisitor, implementationContext);
622 return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);