Rename NodeCodecContext
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / CodecDataObjectAnalysis.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13
14 import com.google.common.base.VerifyException;
15 import com.google.common.collect.ImmutableMap;
16 import java.lang.invoke.MethodHandle;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.MethodType;
19 import java.lang.reflect.Method;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
25 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
26 import org.opendaylight.mdsal.binding.runtime.api.AugmentableRuntimeType;
27 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
28 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
29 import org.opendaylight.yangtools.yang.binding.Augmentable;
30 import org.opendaylight.yangtools.yang.binding.DataContainer;
31 import org.opendaylight.yangtools.yang.binding.DataObject;
32 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
33 import org.opendaylight.yangtools.yang.binding.contract.Naming;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
36
37 /**
38  * Analysis of a {@link DataObject} specialization class. The primary point of this class is to separate out creation
39  * indices needed for {@link #proxyConstructor}. Since we want to perform as much indexing as possible in a single pass,
40  * we also end up indexing things that are not strictly required to arrive at that constructor.
41  */
42 final class CodecDataObjectAnalysis<R extends CompositeRuntimeType> {
43     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
44         AbstractDataObjectCodecContext.class, DataContainerNode.class);
45     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
46         AbstractDataObjectCodecContext.class, DataContainerNode.class);
47
48     final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
49     final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
50     final @NonNull ImmutableMap<NodeIdentifier, CodecContextSupplier> byYang;
51     final @NonNull ImmutableMap<String, ValueNodeCodecContext> leafNodes;
52     final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
53     final @NonNull List<AugmentRuntimeType> possibleAugmentations;
54     final @NonNull MethodHandle proxyConstructor;
55
56     CodecDataObjectAnalysis(final DataContainerCodecPrototype<R> prototype, final CodecItemFactory itemFactory,
57             final Method keyMethod) {
58         // Preliminaries from prototype
59         @SuppressWarnings("unchecked")
60         final Class<DataObject> bindingClass = Class.class.cast(prototype.getBindingClass());
61         final var runtimeType = prototype.getType();
62         final var factory = prototype.getFactory();
63         final var leafContexts = factory.getLeafNodes(bindingClass, runtimeType.statement());
64
65         // Reflection-based on the passed class
66         final var clsToMethod = getChildrenClassToMethod(bindingClass);
67
68         // Indexing part: be very careful around what gets done when
69         final var byYangBuilder = new HashMap<NodeIdentifier, CodecContextSupplier>();
70
71         // Step 1: add leaf children
72         var leafBuilder = ImmutableMap.<String, ValueNodeCodecContext>builderWithExpectedSize(leafContexts.size());
73         for (var leaf : leafContexts.values()) {
74             leafBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
75             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
76         }
77         leafNodes = leafBuilder.build();
78
79         final var byBindingArgClassBuilder = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
80         final var byStreamClassBuilder = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
81         final var daoProperties = new HashMap<Class<?>, PropertyInfo>();
82         for (var childDataObj : clsToMethod.entrySet()) {
83             final var method = childDataObj.getValue();
84             verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
85
86             final var retClass = childDataObj.getKey();
87             if (OpaqueObject.class.isAssignableFrom(retClass)) {
88                 // Filter OpaqueObjects, they are not containers
89                 continue;
90             }
91
92             // Record getter method
93             daoProperties.put(retClass, new PropertyInfo.Getter(method));
94
95             final var childProto = getChildPrototype(runtimeType, factory, itemFactory, retClass);
96             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
97             byYangBuilder.put(childProto.getYangArg(), childProto);
98
99             // FIXME: It really feels like we should be specializing DataContainerCodecPrototype so as to ditch
100             //        createInstance() and then we could do an instanceof check instead.
101             if (childProto.getType() instanceof ChoiceRuntimeType) {
102                 final var choice = (ChoiceNodeCodecContext<?>) childProto.get();
103                 for (var cazeChild : choice.getCaseChildrenClasses()) {
104                     byBindingArgClassBuilder.put(cazeChild, childProto);
105                 }
106             }
107         }
108
109         // Snapshot before below processing
110         byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
111
112         // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
113         // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
114         // byStreamClass for the purposes of both.
115         byBindingArgClassBuilder.putAll(byStreamClassBuilder);
116         byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? byStreamClass
117             : ImmutableMap.copyOf(byBindingArgClassBuilder);
118
119         // Find all non-default nonnullFoo() methods and update the corresponding property info
120         for (var entry : getChildrenClassToNonnullMethod(bindingClass).entrySet()) {
121             final var method = entry.getValue();
122             if (!method.isDefault()) {
123                 daoProperties.compute(entry.getKey(), (key, value) -> new PropertyInfo.GetterAndNonnull(
124                     verifyNotNull(value, "No getter for %s", key).getterMethod(), method));
125             }
126         }
127         // At this point all indexing is done: byYangBuilder should not be referenced
128         byYang = ImmutableMap.copyOf(byYangBuilder);
129
130         // Final bits: generate the appropriate class, As a side effect we identify what Augmentations are possible
131         if (Augmentable.class.isAssignableFrom(bindingClass)) {
132             // Verify we have the appropriate backing runtimeType
133             if (!(runtimeType instanceof AugmentableRuntimeType augmentableRuntimeType)) {
134                 throw new VerifyException(
135                     "Unexpected type %s backing augmenable %s".formatted(runtimeType, bindingClass));
136             }
137
138             possibleAugmentations = augmentableRuntimeType.augments();
139             generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
140                 bindingClass, leafContexts, daoProperties, keyMethod);
141         } else {
142             possibleAugmentations = List.of();
143             generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
144                 leafContexts, daoProperties, keyMethod);
145         }
146
147         // All done: acquire the constructor: it is supposed to be public
148         final MethodHandle ctor;
149         try {
150             ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
151         } catch (NoSuchMethodException | IllegalAccessException e) {
152             throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
153         }
154
155         proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
156     }
157
158     private static @NonNull DataContainerCodecPrototype<?> getChildPrototype(final CompositeRuntimeType type,
159             final CodecContextFactory factory, final CodecItemFactory itemFactory,
160             final Class<? extends DataContainer> childClass) {
161         final var child = type.bindingChild(JavaTypeName.create(childClass));
162         if (child == null) {
163             throw DataContainerCodecContext.childNullException(factory.getRuntimeContext(), childClass,
164                 "Node %s does not have child named %s", type, childClass);
165         }
166
167         return DataContainerCodecPrototype.from(itemFactory.createItem(childClass, child.statement()),
168             (CompositeRuntimeType) child, factory);
169     }
170
171
172     // FIXME: MDSAL-780: these methods perform analytics using java.lang.reflect to acquire the basic shape of the
173     //                   class. This is not exactly AOT friendly, as most of the information should be provided by
174     //                   CompositeRuntimeType.
175     //
176     //                   As as first cut, CompositeRuntimeType should provide the mapping between YANG children and the
177     //                   corresponding GETTER_PREFIX/NONNULL_PREFIX method names, If we have that, the use in this
178     //                   class should be fine.
179     //
180     //                   The second cut is binding the actual Method invocations, which is fine here, as this class is
181     //                   all about having a run-time generated class. AOT would be providing an alternative, where the
182     //                   equivalent class would be generated at compile-time and hence would bind to the methods
183     //                   directly -- and AOT equivalent of this class would really be a compile-time generated registry
184     //                   to those classes' entry points.
185
186     /**
187      * Scans supplied class and returns an iterable of all data children classes.
188      *
189      * @param type YANG Modeled Entity derived from DataContainer
190      * @return Iterable of all data children, which have YANG modeled entity
191      */
192     private static Map<Class<? extends DataContainer>, Method> getChildrenClassToMethod(final Class<?> type) {
193         return getChildClassToMethod(type, Naming.GETTER_PREFIX);
194     }
195
196     private static Map<Class<? extends DataContainer>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
197         return getChildClassToMethod(type, Naming.NONNULL_PREFIX);
198     }
199
200     private static Map<Class<? extends DataContainer>, Method> getChildClassToMethod(final Class<?> type,
201             final String prefix) {
202         checkArgument(type != null, "Target type must not be null");
203         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
204             type);
205         final var ret = new HashMap<Class<? extends DataContainer>, Method>();
206         for (Method method : type.getMethods()) {
207             DataContainerCodecContext.getYangModeledReturnType(method, prefix)
208                 .ifPresent(entity -> ret.put(entity, method));
209         }
210         return ret;
211     }
212 }