Rename yang.binding.{Identifiable,Identifier}
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / CodecDataObjectGenerator.java
index 1c4021ca66ac2dda4b83eb6a470b88d68ca4dde0..f224471e5ec499780e6787339f94cc81396b4fa6 100644 (file)
@@ -41,13 +41,13 @@ import net.bytebuddy.implementation.bytecode.member.MethodReturn;
 import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
 import net.bytebuddy.jar.asm.Opcodes;
 import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.CodecContextSupplierProvider;
 import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
-import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
-import org.opendaylight.mdsal.binding.dom.codec.impl.loader.CodecClassLoader;
-import org.opendaylight.mdsal.binding.dom.codec.impl.loader.CodecClassLoader.ClassGenerator;
-import org.opendaylight.mdsal.binding.dom.codec.impl.loader.CodecClassLoader.GeneratorResult;
-import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
+import org.opendaylight.mdsal.binding.loader.BindingClassLoader;
+import org.opendaylight.mdsal.binding.loader.BindingClassLoader.ClassGenerator;
+import org.opendaylight.mdsal.binding.loader.BindingClassLoader.GeneratorResult;
 import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.contract.Naming;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -59,7 +59,7 @@ import org.slf4j.LoggerFactory;
  * strong connection between a generated class to the extent possible. In most cases (grouping-generated types) this
  * involves one level of indirection, which is a safe approach. If we are dealing with a type generated outside of a
  * grouping statement, though, we are guaranteed instantiation-invariance and hence can hard-wire to a runtime-constant
- * {@link NodeContextSupplier} -- which  provides significant boost to JITs ability to optimize code -- especially with
+ * {@link CodecContextSupplier} -- which  provides significant boost to JITs ability to optimize code -- especially with
  * inlining and constant propagation.
  *
  * <p>
@@ -130,17 +130,17 @@ import org.slf4j.LoggerFactory;
  *
  * <p>
  * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
- * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
+ * and class loading (in {@link BindingClassLoader}). The process is performed in four steps:
  * <ul>
  * <li>During code generation, the context fields are pointed towards
- *     {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
+ *     {@link ClassGeneratorBridge#resolveCodecContextSupplier(String)} and
  *     {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
  *     in the context of a class initializer.</li>
  * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
  *     class loading operation. At this point the generator installs itself as the current generator for this thread via
  *     {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
  * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
- *     point the static invocations will be redirected to {@link #resolveNodeContextSupplier(String)} and
+ *     point the static invocations will be redirected to {@link #resolveCodecContextSupplier(String)} and
  *     {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
  * <li>Before returning from the class loading call, the generator will detach itself via
  *     {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
@@ -155,10 +155,10 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     // FIXME: MDSAL-443: wire this implementation, which requires that BindingRuntimeTypes provides information about
     //                   types being generated from within a grouping
     private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
-            implements NodeContextSupplierProvider<T> {
-        private final ImmutableMap<Method, NodeContextSupplier> properties;
+            implements CodecContextSupplierProvider<T> {
+        private final ImmutableMap<Method, CodecContextSupplier> properties;
 
-        Fixed(final TypeDescription superClass, final ImmutableMap<Method, NodeContextSupplier> properties,
+        Fixed(final TypeDescription superClass, final ImmutableMap<Method, CodecContextSupplier> properties,
                 final @Nullable Method keyMethod) {
             super(superClass, keyMethod);
             this.properties = requireNonNull(properties);
@@ -170,7 +170,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             for (Method method : properties.keySet()) {
                 LOG.trace("Generating for fixed method {}", method);
                 final String methodName = method.getName();
-                final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
+                final TypeDescription retType = ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
                     new SupplierGetterMethodImplementation(methodName, retType));
             }
@@ -178,11 +178,11 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
 
         @Override
-        public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
-            final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
+        public CodecContextSupplier resolveCodecContextSupplier(final String methodName) {
+            final Optional<Entry<Method, CodecContextSupplier>> found = properties.entrySet().stream()
                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
-            return verifyNotNull(found.get().getValue());
+            return verifyNotNull(found.orElseThrow().getValue());
         }
     }
 
@@ -190,10 +190,10 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
             implements LocalNameProvider<T> {
         private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
-        private final Map<Method, Class<?>> daoProperties;
+        private final Map<Class<?>, PropertyInfo> daoProperties;
 
         Reusable(final TypeDescription superClass, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
-                final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
+                final Map<Class<?>, PropertyInfo> daoProperties, final @Nullable Method keyMethod) {
             super(superClass, keyMethod);
             this.simpleProperties = requireNonNull(simpleProperties);
             this.daoProperties = requireNonNull(daoProperties);
@@ -205,17 +205,24 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             for (Method method : simpleProperties.keySet()) {
                 LOG.trace("Generating for simple method {}", method);
                 final String methodName = method.getName();
-                final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
+                final TypeDescription retType = ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
                     new SimpleGetterMethodImplementation(methodName, retType));
             }
-            for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
-                final Method method = entry.getKey();
+            for (Entry<Class<?>, PropertyInfo> entry : daoProperties.entrySet()) {
+                final PropertyInfo info = entry.getValue();
+                final Method method = info.getterMethod();
                 LOG.trace("Generating for structured method {}", method);
                 final String methodName = method.getName();
-                final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
+                final TypeDescription retType = ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
-                    new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
+                        new StructuredGetterMethodImplementation(methodName, retType, entry.getKey()));
+
+                if (info instanceof PropertyInfo.GetterAndNonnull orEmpty) {
+                    final String nonnullName = orEmpty.nonnullMethod().getName();
+                    tmp = tmp.defineMethod(nonnullName, retType, PUB_FINAL).intercept(
+                        new NonnullMethodImplementation(nonnullName, retType, entry.getKey(), method));
+                }
             }
 
             return tmp;
@@ -226,7 +233,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
-            return found.get().getValue().getSchema().getQName().getLocalName();
+            return found.orElseThrow().getValue().getSchema().getQName().getLocalName();
         }
     }
 
@@ -253,23 +260,23 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         this.keyMethod = keyMethod;
     }
 
-    static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
+    static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final BindingClassLoader loader,
             final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
-            final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
-        return loader.generateClass(bindingInterface, "codecImpl",
+            final Map<Class<?>, PropertyInfo> daoProperties, final Method keyMethod) {
+        return CodecPackage.CODEC.generateClass(loader, bindingInterface,
             new Reusable<>(BB_CDO, simpleProperties, daoProperties, keyMethod));
     }
 
     static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
-            final CodecClassLoader loader, final Class<D> bindingInterface,
+            final BindingClassLoader loader, final Class<D> bindingInterface,
             final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
-            final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
-        return loader.generateClass(bindingInterface, "codecImpl",
+            final Map<Class<?>, PropertyInfo> daoProperties, final Method keyMethod) {
+        return CodecPackage.CODEC.generateClass(loader, bindingInterface,
             new Reusable<>(BB_ACDO, simpleProperties, daoProperties, keyMethod));
     }
 
     @Override
-    public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
+    public final GeneratorResult<T> generateClass(final BindingClassLoader loader, final String fqcn,
             final Class<?> bindingInterface) {
         LOG.trace("Generating class {}", fqcn);
 
@@ -283,7 +290,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         if (keyMethod != null) {
             LOG.trace("Generating for key {}", keyMethod);
             final String methodName = keyMethod.getName();
-            final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
+            final TypeDescription retType = ForLoadedType.of(keyMethod.getReturnType());
             builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
                 new KeyMethodImplementation(methodName, retType));
         }
@@ -309,7 +316,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         return new Implementation.Simple(
             // return Foo.bindingHashCode(this);
             loadThis(),
-            invokeMethod(bindingInterface, BindingMapping.BINDING_HASHCODE_NAME, bindingInterface),
+            invokeMethod(bindingInterface, Naming.BINDING_HASHCODE_NAME, bindingInterface),
             MethodReturn.INTEGER);
     }
 
@@ -318,7 +325,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             // return Foo.bindingEquals(this, obj);
             loadThis(),
             FIRST_ARG_REF,
-            invokeMethod(bindingInterface, BindingMapping.BINDING_EQUALS_NAME, bindingInterface, Object.class),
+            invokeMethod(bindingInterface, Naming.BINDING_EQUALS_NAME, bindingInterface, Object.class),
             MethodReturn.INTEGER);
     }
 
@@ -326,14 +333,25 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         return new Implementation.Simple(
             // return Foo.bindingToString(this);
             loadThis(),
-            invokeMethod(bindingInterface, BindingMapping.BINDING_TO_STRING_NAME, bindingInterface),
+            invokeMethod(bindingInterface, Naming.BINDING_TO_STRING_NAME, bindingInterface),
             MethodReturn.REFERENCE);
     }
 
     private abstract static class AbstractMethodImplementation implements Implementation {
+        final TypeDescription retType;
+        // getFoo, usually
+        final String methodName;
+
+        AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
+            this.methodName = requireNonNull(methodName);
+            this.retType = requireNonNull(retType);
+        }
+    }
+
+    private abstract static class AbstractCachedMethodImplementation extends AbstractMethodImplementation {
         private static final Generic BB_HANDLE = TypeDefinition.Sort.describe(VarHandle.class);
         private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
-        private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
+        private static final StackManipulation OBJECT_CLASS = ClassConstant.of(ForLoadedType.of(Object.class));
         private static final StackManipulation LOOKUP = invokeMethod(MethodHandles.class, "lookup");
         private static final StackManipulation FIND_VAR_HANDLE = invokeMethod(Lookup.class,
             "findVarHandle", Class.class, String.class, Class.class);
@@ -342,16 +360,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
                 | Opcodes.ACC_SYNTHETIC;
         private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
 
-        final TypeDescription retType;
-        // getFoo
-        final String methodName;
         // getFoo$$$V
         final String handleName;
 
-        AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
-            this.methodName = requireNonNull(methodName);
-            this.retType = requireNonNull(retType);
-            this.handleName = methodName + "$$$V";
+        AbstractCachedMethodImplementation(final String methodName, final TypeDescription retType) {
+            super(methodName, retType);
+            handleName = methodName + "$$$V";
         }
 
         @Override
@@ -374,7 +388,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
-    private static final class KeyMethodImplementation extends AbstractMethodImplementation {
+    private static final class KeyMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
             "codecKey", VarHandle.class);
 
@@ -394,6 +408,40 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
+    private static final class NonnullMethodImplementation extends AbstractMethodImplementation {
+        private static final StackManipulation NONNULL_MEMBER = invokeMethod(CodecDataObject.class,
+                "codecMemberOrEmpty", Object.class, Class.class);
+
+        private final Class<?> bindingClass;
+        private final Method getterMethod;
+
+        NonnullMethodImplementation(final String methodName, final TypeDescription retType,
+                final Class<?> bindingClass, final Method getterMethod) {
+            super(methodName, retType);
+            this.bindingClass = requireNonNull(bindingClass);
+            this.getterMethod = requireNonNull(getterMethod);
+        }
+
+        @Override
+        public ByteCodeAppender appender(final Target implementationTarget) {
+            return new ByteCodeAppender.Simple(
+                    // return (FooType) codecMemberOrEmpty(getFoo(), FooType.class)
+                    loadThis(),
+                    loadThis(),
+                    invokeMethod(getterMethod),
+                    ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
+                    NONNULL_MEMBER,
+                    TypeCasting.to(retType),
+                    MethodReturn.REFERENCE);
+        }
+
+        @Override
+        public InstrumentedType prepare(final InstrumentedType instrumentedType) {
+            // No-op
+            return instrumentedType;
+        }
+    }
+
     /*
      * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
      * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
@@ -401,7 +449,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
      * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
      * on the constant pool entry to resolve to the same object.
      */
-    private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
+    private static final class SimpleGetterMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
             "codecMember", VarHandle.class, String.class);
         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
@@ -413,7 +461,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
 
         SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
             super(methodName, retType);
-            this.stringName = methodName + "$$$S";
+            stringName = methodName + "$$$S";
         }
 
         @Override
@@ -443,7 +491,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
-    private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
+    private static final class StructuredGetterMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
             "codecMember", VarHandle.class, Class.class);
 
@@ -468,12 +516,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
-    private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
+    private static final class SupplierGetterMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
-            "codecMember", VarHandle.class, NodeContextSupplier.class);
+            "codecMember", VarHandle.class, CodecContextSupplier.class);
         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
             "resolveNodeContextSupplier", String.class);
-        private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
+        private static final Generic BB_NCS = TypeDefinition.Sort.describe(CodecContextSupplier.class);
 
         // getFoo$$$C
         private final String contextName;