Pick up byte-buddy from yangtools
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.java
index b63befcbe96f7ef77125fe1664cbf69ff309e555..3335246efaa90853f6d7381b9b3fd29a1713dd0e 100644 (file)
@@ -10,14 +10,19 @@ package org.opendaylight.mdsal.binding.dom.codec.impl;
 import static com.google.common.base.Preconditions.checkArgument;
 
 import com.google.common.annotations.Beta;
+import com.google.common.base.Throwables;
+import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableCollection;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
 import java.lang.invoke.VarHandle;
 import java.lang.reflect.Method;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
@@ -26,19 +31,20 @@ import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCaching
 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
 import org.opendaylight.mdsal.binding.model.api.Type;
 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
-import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
+import org.opendaylight.mdsal.binding.runtime.api.AugmentableRuntimeType;
 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
+import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
 import org.opendaylight.yangtools.yang.binding.BindingObject;
 import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.DataObjectStep;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -52,6 +58,10 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         permits CaseCodecContext, ContainerLikeCodecContext, ListCodecContext, NotificationCodecContext {
     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
 
+    private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
+        AbstractDataObjectCodecContext.class, DataContainerNode.class);
+    private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
+        DataObjectCodecContext.class, DataContainerNode.class);
     private static final VarHandle MISMATCHED_AUGMENTED;
 
     static {
@@ -63,9 +73,10 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         }
     }
 
-    private final ImmutableMap<Class<?>, AugmentationCodecPrototype> augmentToPrototype;
+    private final ImmutableMap<Class<?>, AugmentationCodecPrototype<?>> augmentToPrototype;
     private final ImmutableMap<NodeIdentifier, Class<?>> yangToAugmentClass;
     private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
+    private final MethodHandle proxyConstructor;
 
     // Note this the content of this field depends only of invariants expressed as this class's fields or
     // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
@@ -74,31 +85,61 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
     private volatile ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
 
     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype) {
-        this(prototype, CodecItemFactory.of());
+        this(prototype, new DataContainerAnalysis<>(prototype), null);
     }
 
-    DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
-        this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
+    DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
+            final Class<? extends DataObject> caseClass) {
+        this(prototype, new DataContainerAnalysis<>(prototype, caseClass), null);
     }
 
     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final Method keyMethod) {
-        this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
+        this(prototype, new DataContainerAnalysis<>(prototype), keyMethod);
     }
 
     private DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
-            final CodecDataObjectAnalysis<T> analysis) {
+            final DataContainerAnalysis<T> analysis, final Method keyMethod) {
         super(prototype, analysis);
 
-        // Inherit analysis stuff
-        generatedClass = analysis.generatedClass;
+        final var bindingClass = getBindingClass();
+
+        // Final bits: generate the appropriate class, As a side effect we identify what Augmentations are possible
+        final List<AugmentRuntimeType> possibleAugmentations;
+        final var loader = prototype().contextFactory().getLoader();
+        if (Augmentable.class.isAssignableFrom(bindingClass)) {
+            // Verify we have the appropriate backing runtimeType
+            final var runtimeType = prototype.runtimeType();
+            if (!(runtimeType instanceof AugmentableRuntimeType augmentableRuntimeType)) {
+                throw new VerifyException(
+                    "Unexpected type %s backing augmenable %s".formatted(runtimeType, bindingClass));
+            }
+
+            possibleAugmentations = augmentableRuntimeType.augments();
+            generatedClass = CodecDataObjectGenerator.generateAugmentable(loader, bindingClass, analysis.leafContexts,
+                analysis.daoProperties, keyMethod);
+        } else {
+            possibleAugmentations = List.of();
+            generatedClass = CodecDataObjectGenerator.generate(loader, bindingClass, analysis.leafContexts,
+                analysis.daoProperties, keyMethod);
+        }
+
+        // All done: acquire the constructor: it is supposed to be public
+        final MethodHandle ctor;
+        try {
+            ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
+        } catch (NoSuchMethodException | IllegalAccessException e) {
+            throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
+        }
+
+        proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
 
         // Deal with augmentations, which are not something we analysis provides
         final var augPathToBinding = new HashMap<NodeIdentifier, Class<?>>();
-        final var augClassToProto = new HashMap<Class<?>, AugmentationCodecPrototype>();
-        for (var augment : analysis.possibleAugmentations) {
+        final var augClassToProto = new HashMap<Class<?>, AugmentationCodecPrototype<?>>();
+        for (var augment : possibleAugmentations) {
             final var augProto = loadAugmentPrototype(augment);
             if (augProto != null) {
-                final var augBindingClass = augProto.getBindingClass();
+                final var augBindingClass = augProto.javaClass();
                 for (var childPath : augProto.getChildArgs()) {
                     augPathToBinding.putIfAbsent(childPath, augBindingClass);
                 }
@@ -110,13 +151,13 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
     }
 
     @Override
-    final CommonDataObjectCodecPrototype<?> pathChildPrototype(final Class<? extends DataObject> argType) {
+    final DataContainerPrototype<?, ?> pathChildPrototype(final Class<? extends DataObject> argType) {
         final var child = super.pathChildPrototype(argType);
         return child != null ? child : augmentToPrototype.get(argType);
     }
 
     @Override
-    final CommonDataObjectCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
+    final DataContainerPrototype<?, ?> streamChildPrototype(final Class<?> childClass) {
         final var child = super.streamChildPrototype(childClass);
         if (child == null && Augmentation.class.isAssignableFrom(childClass)) {
             return getAugmentationProtoByClass(childClass);
@@ -136,24 +177,24 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         return child;
     }
 
-    private @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
+    private @Nullable AugmentationCodecPrototype<?> getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
         final var childProto = augmentToPrototype.get(augmClass);
         return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
     }
 
-    private @Nullable AugmentationCodecPrototype mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
+    private @Nullable AugmentationCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
         /*
          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
          * we'll cache it so we do not need to perform reflection operations again.
          */
-        final var local = (ImmutableMap<Class<?>, AugmentationCodecPrototype>) MISMATCHED_AUGMENTED.getAcquire(this);
+        final var local = (ImmutableMap<Class<?>, AugmentationCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
         final var mismatched = local.get(childClass);
         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
     }
 
-    private @Nullable AugmentationCodecPrototype loadMismatchedAugmentation(
-            final ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
+    private @Nullable AugmentationCodecPrototype<?> loadMismatchedAugmentation(
+            final ImmutableMap<Class<?>, AugmentationCodecPrototype<?>> oldMismatched,
             final @NonNull Class<?> childClass) {
         @SuppressWarnings("rawtypes")
         final Class<?> augTarget = findAugmentationTarget((Class) childClass);
@@ -161,8 +202,8 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         // context would load.
         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
             for (var realChild : augmentToPrototype.values()) {
-                if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
-                        && isSubstitutionFor(childClass, realChild.getBindingClass())) {
+                final var realClass = realChild.javaClass();
+                if (Augmentation.class.isAssignableFrom(realClass) && isSubstitutionFor(childClass, realClass)) {
                     return cacheMismatched(oldMismatched, childClass, realChild);
                 }
             }
@@ -171,9 +212,9 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         return null;
     }
 
-    private @NonNull AugmentationCodecPrototype cacheMismatched(
-            final @NonNull ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
-            final @NonNull Class<?> childClass, final @NonNull AugmentationCodecPrototype prototype) {
+    private @NonNull AugmentationCodecPrototype<?> cacheMismatched(
+            final @NonNull ImmutableMap<Class<?>, AugmentationCodecPrototype<?>> oldMismatched,
+            final @NonNull Class<?> childClass, final @NonNull AugmentationCodecPrototype<?> prototype) {
         var expected = oldMismatched;
         while (true) {
             final var newMismatched =
@@ -182,7 +223,7 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
                     .put(childClass, prototype)
                     .build();
 
-            final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype>)
+            final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype<?>>)
                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
             if (witness == expected) {
                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
@@ -199,7 +240,7 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
     }
 
     private boolean belongsToRuntimeContext(final Class<?> cls) {
-        final BindingRuntimeContext ctx = factory().getRuntimeContext();
+        final var ctx = prototype().contextFactory().getRuntimeContext();
         final Class<?> loaded;
         try {
             loaded = ctx.loadClass(Type.of(cls));
@@ -210,7 +251,7 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         return cls.equals(loaded);
     }
 
-    private @Nullable AugmentationCodecPrototype loadAugmentPrototype(final AugmentRuntimeType augment) {
+    private @Nullable AugmentationCodecPrototype<?> loadAugmentPrototype(final AugmentRuntimeType augment) {
         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
         //        declaration site
         final var childPaths = augment.statement()
@@ -222,7 +263,7 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
             return null;
         }
 
-        final var factory = factory();
+        final var factory = prototype().contextFactory();
         final GeneratedType javaType = augment.javaType();
         final Class<? extends Augmentation<?>> augClass;
         try {
@@ -231,7 +272,7 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
             throw new IllegalStateException(
                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
         }
-        return new AugmentationCodecPrototype(augClass, augment, factory, childPaths);
+        return new AugmentationCodecPrototype<>(augClass, augment, factory, childPaths);
     }
 
     @Override
@@ -241,12 +282,12 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
          * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
          * aggregated into own container node, then only deserialized using associated prototype.
          */
-        final var builders = new HashMap<Class<?>, DataContainerNodeBuilder>();
+        final var builders = new HashMap<Class<?>, DataContainerNodeBuilder<?, ?>>();
         for (var childValue : data.body()) {
             final var bindingClass = yangToAugmentClass.get(childValue.name());
             if (bindingClass != null) {
                 builders.computeIfAbsent(bindingClass,
-                    key -> Builders.containerBuilder()
+                    key -> ImmutableNodes.newContainerBuilder()
                         .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
                         .addChild(childValue);
             }
@@ -257,7 +298,7 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
             final var bindingClass = entry.getKey();
             final var codecProto = augmentToPrototype.get(bindingClass);
             if (codecProto != null) {
-                final var bindingObj = codecProto.get().deserializeObject(entry.getValue().build());
+                final var bindingObj = codecProto.getCodecContext().deserializeObject(entry.getValue().build());
                 if (bindingObj != null) {
                     map.put(bindingClass, bindingObj);
                 }
@@ -266,19 +307,15 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
         return map;
     }
 
-    final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
-        return generatedClass;
-    }
-
     @Override
-    public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
+    public DataObjectStep<?> deserializePathArgument(final PathArgument arg) {
         checkArgument(getDomPathArgument().equals(arg));
         return bindingArg();
     }
 
     @Override
-    public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
-        checkArgument(bindingArg().equals(arg));
+    public PathArgument serializePathArgument(final DataObjectStep<?> step) {
+        checkArgument(bindingArg().equals(step));
         return getDomPathArgument();
     }
 
@@ -292,4 +329,23 @@ public abstract sealed class DataObjectCodecContext<D extends DataObject, T exte
             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
         return createCachingCodec(this, cacheSpecifier);
     }
+
+    final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
+        return generatedClass;
+    }
+
+    @SuppressWarnings("checkstyle:illegalCatch")
+    final @NonNull D createBindingProxy(final DataContainerNode node) {
+        try {
+            return (D) proxyConstructor.invokeExact(this, node);
+        } catch (final Throwable e) {
+            Throwables.throwIfUnchecked(e);
+            throw new IllegalStateException(e);
+        }
+    }
+
+    @Override
+    Object deserializeObject(final NormalizedNode normalizedNode) {
+        return deserialize(normalizedNode);
+    }
 }