Bump upstreams
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.java
index 9dcd71387447c76f8cbd7a95568e96ae353f9a6e..b63befcbe96f7ef77125fe1664cbf69ff309e555 100644 (file)
@@ -9,395 +9,287 @@ package org.opendaylight.mdsal.binding.dom.codec.impl;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
-import com.google.common.base.Throwables;
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ImmutableCollection;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSortedMap;
+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.reflect.InvocationHandler;
+import java.lang.invoke.VarHandle;
 import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.Collection;
-import java.util.Comparator;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.SortedMap;
-import java.util.TreeMap;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
+import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
+import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
+import org.opendaylight.mdsal.binding.model.api.GeneratedType;
 import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
-import org.opendaylight.yangtools.yang.binding.Augmentable;
+import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
+import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
+import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
+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.InstanceIdentifier.Item;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+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.NormalizedNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
-import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
+import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
-        extends DataContainerCodecContext<D, T> {
+/**
+ * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
+ */
+@Beta
+public abstract sealed class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
+        extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D>
+        permits CaseCodecContext, ContainerLikeCodecContext, ListCodecContext, NotificationCodecContext {
     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
-    private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
-    private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
-    private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
-
-    private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
-    private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
-    private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
-    private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
-    private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
-    private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
-    private final MethodHandle proxyConstructor;
-
-    private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
-            new ConcurrentHashMap<>();
-    private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
-
-    DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
-        super(prototype);
-
-        final Class<D> bindingClass = getBindingClass();
-        this.leafChild = factory().getLeafNodes(bindingClass, getSchema());
-
-        final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
-
-        final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
-        final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
-        final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
-        final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
-
-        // Adds leaves to mapping
-        for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
-            byMethodBuilder.put(leaf.getGetter(), leaf);
-            byYangBuilder.put(leaf.getDomPathArgument(), leaf);
-        }
 
-        for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
-            final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
-            byMethodBuilder.put(childDataObj.getValue(), childProto);
-            byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
-            byYangBuilder.put(childProto.getYangArg(), childProto);
-            if (childProto.isChoice()) {
-                final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
-                for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
-                    byBindingArgClassBuilder.put(cazeChild, childProto);
-                }
-            }
-        }
-        this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
-        this.byYang = ImmutableMap.copyOf(byYangBuilder);
-        this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
-        byBindingArgClassBuilder.putAll(byStreamClass);
-        this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
-
-        if (Augmentable.class.isAssignableFrom(bindingClass)) {
-            this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
-        } else {
-            this.possibleAugmentations = ImmutableMap.of();
-        }
-        reloadAllAugmentations();
+    private static final VarHandle MISMATCHED_AUGMENTED;
 
-        final Class<?> proxyClass = Proxy.getProxyClass(bindingClass.getClassLoader(), bindingClass,
-            AugmentationHolder.class);
+    static {
         try {
-            proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
-                    .asType(DATAOBJECT_TYPE);
-        } catch (NoSuchMethodException | IllegalAccessException e) {
-            throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
+            MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
+                "mismatchedAugmented", ImmutableMap.class);
+        } catch (NoSuchFieldException | IllegalAccessException e) {
+            throw new ExceptionInInitializerError(e);
         }
     }
 
-    @SuppressFBWarnings("RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED")
-    private void reloadAllAugmentations() {
-        for (final Type augment : possibleAugmentations.values()) {
-            final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
-            if (augProto != null) {
-                byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
-                byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
-            }
-        }
-    }
+    private final ImmutableMap<Class<?>, AugmentationCodecPrototype> augmentToPrototype;
+    private final ImmutableMap<NodeIdentifier, Class<?>> yangToAugmentClass;
+    private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
 
-    @SuppressWarnings("unchecked")
-    @Override
-    public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
-        final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
-        return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
-                childClass).get();
+    // 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.
+    @SuppressWarnings("unused")
+    @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
+    private volatile ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
+
+    DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype) {
+        this(prototype, CodecItemFactory.of());
     }
 
-    private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
-        final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
-        if (childProto != null) {
-            return childProto;
-        }
-        if (Augmentation.class.isAssignableFrom(childClass)) {
-            return augmentationByClass(childClass);
-        }
-        return null;
+    DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
+        this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
     }
 
-    @SuppressWarnings("unchecked")
-    @Override
-    public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
-            final Class<C> childClass) {
-        final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
-        if (childProto != null) {
-            return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
-        }
-        return Optional.empty();
+    DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final Method keyMethod) {
+        this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
     }
 
-    @Override
-    public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
-            final List<YangInstanceIdentifier.PathArgument> builder) {
+    private DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
+            final CodecDataObjectAnalysis<T> analysis) {
+        super(prototype, analysis);
 
-        final Class<? extends DataObject> argType = arg.getType();
-        DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
-        if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
-            ctxProto = augmentationByClass(argType);
-        }
-        final DataContainerCodecContext<?, ?> context =
-                childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
-        if (context instanceof ChoiceNodeCodecContext) {
-            final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
-            choice.addYangPathArgument(arg, builder);
-
-            final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
-            final Class<? extends DataObject> type = arg.getType();
-            final DataContainerCodecContext<?, ?> caze;
-            if (caseType.isPresent()) {
-                // Non-ambiguous addressing this should not pose any problems
-                caze = choice.streamChild(caseType.get());
-            } else {
-                caze = choice.getCaseByChildClass(type);
-            }
+        // Inherit analysis stuff
+        generatedClass = analysis.generatedClass;
 
-            caze.addYangPathArgument(arg, builder);
-            return caze.bindingPathArgumentChild(arg, builder);
+        // 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 augProto = loadAugmentPrototype(augment);
+            if (augProto != null) {
+                final var augBindingClass = augProto.getBindingClass();
+                for (var childPath : augProto.getChildArgs()) {
+                    augPathToBinding.putIfAbsent(childPath, augBindingClass);
+                }
+                augClassToProto.putIfAbsent(augBindingClass, augProto);
+            }
         }
-        context.addYangPathArgument(arg, builder);
-        return context;
+        yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
+        augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
     }
 
-    @SuppressWarnings("unchecked")
     @Override
-    public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
-        final NodeContextSupplier childSupplier;
-        if (arg instanceof NodeIdentifierWithPredicates) {
-            childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
-        } else if (arg instanceof AugmentationIdentifier) {
-            childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
-        } else {
-            childSupplier = byYang.get(arg);
-        }
-
-        return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
-            "Argument %s is not valid child of %s", arg, getSchema()).get();
+    final CommonDataObjectCodecPrototype<?> pathChildPrototype(final Class<? extends DataObject> argType) {
+        final var child = super.pathChildPrototype(argType);
+        return child != null ? child : augmentToPrototype.get(argType);
     }
 
-    protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
-        final LeafNodeCodecContext<?> value = leafChild.get(name);
-        return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
+    @Override
+    final CommonDataObjectCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
+        final var child = super.streamChildPrototype(childClass);
+        if (child == null && Augmentation.class.isAssignableFrom(childClass)) {
+            return getAugmentationProtoByClass(childClass);
+        }
+        return child;
     }
 
-    private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
-        final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
-        // Direct instantiation or use in same module in which grouping
-        // was defined.
-        DataSchemaNode sameName;
-        try {
-            sameName = getSchema().getDataChildByName(origDef.getQName());
-        } catch (final IllegalArgumentException e) {
-            sameName = null;
-        }
-        final DataSchemaNode childSchema;
-        if (sameName != null) {
-            // Exactly same schema node
-            if (origDef.equals(sameName)) {
-                childSchema = sameName;
-                // We check if instantiated node was added via uses
-                // statement and is instantiation of same grouping
-            } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
-                childSchema = sameName;
-            } else {
-                // Node has same name, but clearly is different
-                childSchema = null;
-            }
-        } else {
-            // We are looking for instantiation via uses in other module
-            final QName instantiedName = origDef.getQName().withModule(namespace());
-            final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
-            // We check if it is really instantiated from same
-            // definition as class was derived
-            if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
-                childSchema = potential;
-            } else {
-                childSchema = null;
+    @Override
+    final CodecContextSupplier yangChildSupplier(final NodeIdentifier arg) {
+        final var child = super.yangChildSupplier(arg);
+        if (child == null) {
+            final var augClass = yangToAugmentClass.get(arg);
+            if (augClass != null) {
+                return augmentToPrototype.get(augClass);
             }
         }
-        final DataSchemaNode nonNullChild =
-                childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
-        return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
+        return child;
     }
 
-    @SuppressWarnings("unchecked")
-    Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
-        return Item.of((Class<? extends DataObject>) childClass);
+    private @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
+        final var childProto = augmentToPrototype.get(augmClass);
+        return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
     }
 
-    private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
-        final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
-        if (firstTry != null) {
-            return firstTry;
-        }
-        if (possibleAugmentations.containsKey(arg)) {
-            reloadAllAugmentations();
-            return byYangAugmented.get(arg);
-        }
-        return null;
-    }
-
-    private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
-        final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
-        if (firstTry != null) {
-            return firstTry;
-        }
-        reloadAllAugmentations();
-        return augmentationByClassOrEquivalentClass(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 mismatched = local.get(childClass);
+        return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
     }
 
-    private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
+    private @Nullable AugmentationCodecPrototype loadMismatchedAugmentation(
+            final ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
             final @NonNull Class<?> childClass) {
-        final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
-        if (childProto != null) {
-            return childProto;
-        }
-
-        /*
-         * It is potentially mismatched valid augmentation - we look up equivalent augmentation
-         * using reflection and walk all stream child and compare augmenations classes if they are
-         * equivalent.
-         *
-         * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
-         */
         @SuppressWarnings("rawtypes")
-        final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
-        if (getBindingClass().equals(augTarget)) {
-            for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
+        final Class<?> augTarget = findAugmentationTarget((Class) childClass);
+        // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
+        // context would load.
+        if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
+            for (var realChild : augmentToPrototype.values()) {
                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
-                        && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
-                    return realChild;
+                        && isSubstitutionFor(childClass, realChild.getBindingClass())) {
+                    return cacheMismatched(oldMismatched, childClass, realChild);
                 }
             }
         }
+        LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
         return null;
     }
 
-    private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
-        final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
-        @SuppressWarnings("rawtypes")
-        final Class augClass;
-        try {
-            augClass = loader.loadClass(value);
-        } catch (final ClassNotFoundException e) {
-            LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
-            return null;
+    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 =
+                ImmutableMap.<Class<?>, CommonDataObjectCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
+                    .putAll(expected)
+                    .put(childClass, prototype)
+                    .build();
+
+            final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype>)
+                MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
+            if (witness == expected) {
+                LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
+                return prototype;
+            }
+
+            expected = witness;
+            final var existing = expected.get(childClass);
+            if (existing != null) {
+                LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
+                return existing;
+            }
         }
+    }
 
-        @SuppressWarnings("unchecked")
-        final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
-                .getResolvedAugmentationSchema(getSchema(), augClass);
-        return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
+    private boolean belongsToRuntimeContext(final Class<?> cls) {
+        final BindingRuntimeContext ctx = factory().getRuntimeContext();
+        final Class<?> loaded;
+        try {
+            loaded = ctx.loadClass(Type.of(cls));
+        } catch (ClassNotFoundException e) {
+            LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
+            return false;
+        }
+        return cls.equals(loaded);
     }
 
-    @SuppressWarnings("rawtypes")
-    Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
-        final NodeCodecContext<?> childContext = byMethod.get(method).get();
-        @SuppressWarnings("unchecked")
-        final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
-        if (domChild.isPresent()) {
-            return childContext.deserializeObject(domChild.get());
-        } else if (childContext instanceof LeafNodeCodecContext) {
-            return ((LeafNodeCodecContext)childContext).defaultObject();
-        } else {
+    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()
+            .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
+            .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
+            .collect(ImmutableSet.toImmutableSet());
+
+        if (childPaths.isEmpty()) {
             return null;
         }
-    }
 
-    @SuppressWarnings("checkstyle:illegalCatch")
-    protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
+        final var factory = factory();
+        final GeneratedType javaType = augment.javaType();
+        final Class<? extends Augmentation<?>> augClass;
         try {
-            return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
-        } catch (final Throwable e) {
-            Throwables.throwIfUnchecked(e);
-            throw new RuntimeException(e);
+            augClass = factory.getRuntimeContext().loadClass(javaType);
+        } catch (final ClassNotFoundException e) {
+            throw new IllegalStateException(
+                "RuntimeContext references type " + javaType + " but failed to load its class", e);
         }
+        return new AugmentationCodecPrototype(augClass, augment, factory, childPaths);
     }
 
+    @Override
     @SuppressWarnings("unchecked")
-    Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
-            final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
-
-        @SuppressWarnings("rawtypes")
-        final Map map = new HashMap<>();
-
-        for (final NormalizedNode<?, ?> childValue : data.getValue()) {
-            if (childValue instanceof AugmentationNode) {
-                final AugmentationNode augDomNode = (AugmentationNode) childValue;
-                final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
-                if (codecProto != null) {
-                    final DataContainerCodecContext<?, ?> codec = codecProto.get();
-                    map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
-                }
+    Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
+        /**
+         * 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>();
+        for (var childValue : data.body()) {
+            final var bindingClass = yangToAugmentClass.get(childValue.name());
+            if (bindingClass != null) {
+                builders.computeIfAbsent(bindingClass,
+                    key -> Builders.containerBuilder()
+                        .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
+                        .addChild(childValue);
             }
         }
-        for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
-            final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
-            if (augData.isPresent()) {
-                map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
+        @SuppressWarnings("rawtypes")
+        final var map = new HashMap();
+        for (final var entry : builders.entrySet()) {
+            final var bindingClass = entry.getKey();
+            final var codecProto = augmentToPrototype.get(bindingClass);
+            if (codecProto != null) {
+                final var bindingObj = codecProto.get().deserializeObject(entry.getValue().build());
+                if (bindingObj != null) {
+                    map.put(bindingClass, bindingObj);
+                }
             }
         }
         return map;
     }
 
-    Collection<Method> getHashCodeAndEqualsMethods() {
-        return byMethod.keySet();
+    final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
+        return generatedClass;
     }
 
     @Override
-    public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
+    public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
         checkArgument(getDomPathArgument().equals(arg));
         return bindingArg();
     }
 
     @Override
-    public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
+    public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
         checkArgument(bindingArg().equals(arg));
         return getDomPathArgument();
     }
+
+    @Override
+    public NormalizedNode serialize(final D data) {
+        return serializeImpl(data);
+    }
+
+    @Override
+    public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
+            final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
+        return createCachingCodec(this, cacheSpecifier);
+    }
 }