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