Add YangData base interface
[yangtools.git] / binding / mdsal-binding-generator / src / main / java / org / opendaylight / mdsal / binding / generator / impl / reactor / Generator.java
1 /*
2  * Copyright (c) 2021 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.generator.impl.reactor;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.mdsal.binding.model.ri.Types.STRING;
13 import static org.opendaylight.mdsal.binding.model.ri.Types.classType;
14 import static org.opendaylight.mdsal.binding.model.ri.Types.primitiveBooleanType;
15 import static org.opendaylight.mdsal.binding.model.ri.Types.primitiveIntType;
16 import static org.opendaylight.mdsal.binding.model.ri.Types.wildcardTypeFor;
17
18 import com.google.common.base.MoreObjects;
19 import com.google.common.base.MoreObjects.ToStringHelper;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Optional;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.opendaylight.mdsal.binding.generator.impl.reactor.CollisionDomain.Member;
27 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
28 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
29 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
30 import org.opendaylight.mdsal.binding.model.api.Type;
31 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
32 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
33 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
36 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
37 import org.opendaylight.mdsal.binding.model.ri.Types;
38 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.GeneratedPropertyBuilderImpl;
39 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
40 import org.opendaylight.yangtools.yang.binding.DataContainer;
41 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.ri.type.TypeBuilder;
45 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
46
47 /**
48  * A single node in generator tree. Each node will eventually resolve to a generated Java class. Each node also can have
49  * a number of children, which are generators corresponding to the YANG subtree of this node.
50  *
51  * <p>
52  * Each tree is rooted in a {@link ModuleGenerator} and its organization follows roughly YANG {@code schema tree}
53  * layout, but with a twist coming from the reuse of generated interfaces from a {@code grouping} in the location of
54  * every {@code uses} encountered and also the corresponding backwards propagation of {@code augment} effects.
55  *
56  * <p>
57  * Overall the tree layout guides the allocation of Java package and top-level class namespaces.
58  */
59 public abstract class Generator implements Iterable<Generator> {
60     static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
61     static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
62
63     private final AbstractCompositeGenerator<?, ?> parent;
64
65     private Optional<Member> member;
66     private GeneratorResult result;
67     private JavaTypeName typeName;
68     private String javaPackage;
69
70     Generator() {
71         parent = null;
72     }
73
74     Generator(final AbstractCompositeGenerator<?, ?> parent) {
75         this.parent = requireNonNull(parent);
76     }
77
78     public final @NonNull Optional<GeneratedType> generatedType() {
79         return Optional.ofNullable(result.generatedType());
80     }
81
82     public @NonNull List<GeneratedType> auxiliaryGeneratedTypes() {
83         return List.of();
84     }
85
86     @Override
87     public Iterator<Generator> iterator() {
88         return Collections.emptyIterator();
89     }
90
91     /**
92      * Return the {@link AbstractCompositeGenerator} inside which this generator is defined. It is illegal to call this
93      * method on a {@link ModuleGenerator}.
94      *
95      * @return Parent generator
96      */
97     final @NonNull AbstractCompositeGenerator<?, ?> getParent() {
98         return verifyNotNull(parent, "No parent for %s", this);
99     }
100
101     boolean isEmpty() {
102         return true;
103     }
104
105     /**
106      * Return the namespace of this statement.
107      *
108      * @return Corresponding namespace
109      * @throws UnsupportedOperationException if this node does not have a corresponding namespace
110      */
111     @NonNull StatementNamespace namespace() {
112         return StatementNamespace.DEFAULT;
113     }
114
115     @NonNull ModuleGenerator currentModule() {
116         return getParent().currentModule();
117     }
118
119     /**
120      * Push this statement into a {@link SchemaInferenceStack} so that the stack contains a resolvable {@code data tree}
121      * hierarchy.
122      *
123      * @param inferenceStack Target inference stack
124      */
125     abstract void pushToInference(@NonNull SchemaInferenceStack inferenceStack);
126
127     abstract @NonNull ClassPlacement classPlacement();
128
129     final @NonNull Member getMember() {
130         return verifyNotNull(ensureMember(), "No member for %s", this);
131     }
132
133     final Member ensureMember() {
134         if (member == null) {
135             member = switch (classPlacement()) {
136                 case NONE -> Optional.empty();
137                 case MEMBER, PHANTOM, TOP_LEVEL -> Optional.of(createMember(parentDomain()));
138             };
139         }
140         return member.orElse(null);
141     }
142
143     @NonNull CollisionDomain parentDomain() {
144         return getParent().domain();
145     }
146
147     abstract @NonNull Member createMember(@NonNull CollisionDomain domain);
148
149     /**
150      * Create the type associated with this builder. This method idempotent.
151      *
152      * @param builderFactory Factory for {@link TypeBuilder}s
153      * @throws NullPointerException if {@code builderFactory} is {@code null}
154      */
155     final void ensureType(final TypeBuilderFactory builderFactory) {
156         if (result != null) {
157             return;
158         }
159
160         result = switch (classPlacement()) {
161             case NONE, PHANTOM -> GeneratorResult.empty();
162             case MEMBER -> GeneratorResult.member(createTypeImpl(requireNonNull(builderFactory)));
163             case TOP_LEVEL -> GeneratorResult.toplevel(createTypeImpl(requireNonNull(builderFactory)));
164         };
165
166         for (Generator child : this) {
167             child.ensureType(builderFactory);
168         }
169     }
170
171     @NonNull GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
172         return verifyNotNull(tryGeneratedType(builderFactory), "No type generated for %s", this);
173     }
174
175     final @Nullable GeneratedType tryGeneratedType(final TypeBuilderFactory builderFactory) {
176         ensureType(builderFactory);
177         return result.generatedType();
178     }
179
180     final @Nullable GeneratedType enclosedType(final TypeBuilderFactory builderFactory) {
181         ensureType(builderFactory);
182         return result.enclosedType();
183     }
184
185     /**
186      * Create the type associated with this builder, as per {@link #ensureType(TypeBuilderFactory)} contract. This
187      * method is guaranteed to be called at most once.
188      *
189      * @param builderFactory Factory for {@link TypeBuilder}s
190      */
191     abstract @NonNull GeneratedType createTypeImpl(@NonNull TypeBuilderFactory builderFactory);
192
193     final @NonNull String assignedName() {
194         return getMember().currentClass();
195     }
196
197     final @NonNull String javaPackage() {
198         String local = javaPackage;
199         if (local == null) {
200             javaPackage = local = createJavaPackage();
201         }
202         return local;
203     }
204
205     @NonNull String createJavaPackage() {
206         final String parentPackage = getPackageParent().javaPackage();
207         final String myPackage = getMember().currentPackage();
208         return BindingMapping.normalizePackageName(parentPackage + '.' + myPackage);
209     }
210
211     final @NonNull JavaTypeName typeName() {
212         JavaTypeName local = typeName;
213         if (local == null) {
214             typeName = local = createTypeName();
215         }
216         return local;
217     }
218
219     @NonNull JavaTypeName createTypeName() {
220         return JavaTypeName.create(getPackageParent().javaPackage(), assignedName());
221     }
222
223     @NonNull AbstractCompositeGenerator<?, ?> getPackageParent() {
224         return getParent();
225     }
226
227     @Override
228     public final String toString() {
229         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
230     }
231
232     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
233         return helper;
234     }
235
236     final void addImplementsChildOf(final GeneratedTypeBuilder builder) {
237         AbstractCompositeGenerator<?, ?> ancestor = getParent();
238         while (true) {
239             // choice/case hierarchy does not factor into 'ChildOf' hierarchy, hence we need to skip them
240             if (ancestor instanceof CaseGenerator || ancestor instanceof ChoiceGenerator) {
241                 ancestor = ancestor.getParent();
242                 continue;
243             }
244
245             // if we into a choice we need to follow the hierararchy of that choice
246             if (ancestor instanceof AbstractAugmentGenerator augment
247                 && augment.targetGenerator() instanceof ChoiceGenerator targetChoice) {
248                 ancestor = targetChoice;
249                 continue;
250             }
251
252             break;
253         }
254
255         builder.addImplementsType(BindingTypes.childOf(Type.of(ancestor.typeName())));
256     }
257
258     /**
259      * Add common methods implemented in a generated type. This includes {@link DataContainer#implementedInterface()} as
260      * well has {@code bindingHashCode()}, {@code bindingEquals()} and {@code bindingToString()}.
261      *
262      * @param builder Target builder
263      */
264     static final void addConcreteInterfaceMethods(final GeneratedTypeBuilder builder) {
265         defaultImplementedInterace(builder);
266
267         builder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
268             .setAccessModifier(AccessModifier.PUBLIC)
269             .setStatic(true)
270             .setReturnType(primitiveIntType());
271         builder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
272             .setAccessModifier(AccessModifier.PUBLIC)
273             .setStatic(true)
274             .setReturnType(primitiveBooleanType());
275         builder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
276             .setAccessModifier(AccessModifier.PUBLIC)
277             .setStatic(true)
278             .setReturnType(STRING);
279     }
280
281     static final void annotateDeprecatedIfNecessary(final EffectiveStatement<?, ?> stmt,
282             final AnnotableTypeBuilder builder) {
283         if (stmt instanceof WithStatus withStatus) {
284             annotateDeprecatedIfNecessary(withStatus, builder);
285         }
286     }
287
288     static final void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
289         switch (node.getStatus()) {
290             case DEPRECATED ->
291                 // FIXME: we really want to use a pre-made annotation
292                 builder.addAnnotation(DEPRECATED_ANNOTATION);
293             case OBSOLETE -> builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
294             case CURRENT -> {
295                 // No-op
296             }
297             default -> throw new IllegalStateException("Unhandled status in " + node);
298         }
299     }
300
301     static final void addUnits(final GeneratedTOBuilder builder, final TypeDefinition<?> typedef) {
302         typedef.getUnits().ifPresent(units -> {
303             if (!units.isEmpty()) {
304                 builder.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
305                 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
306                 prop.setReturnType(Types.STRING);
307                 builder.addToStringProperty(prop);
308             }
309         });
310     }
311
312     /**
313      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
314      * property.
315      *
316      * @param builder transfer object which needs to be made serializable
317      */
318     static final void makeSerializable(final GeneratedTOBuilder builder) {
319         builder.addImplementsType(Types.serializableType());
320         addSerialVersionUID(builder);
321     }
322
323     static final void addSerialVersionUID(final GeneratedTOBuilder gto) {
324         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
325         prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
326         gto.setSUID(prop);
327     }
328
329     /**
330      * Add a {@link DataContainer#implementedInterface()} declaration with a narrower return type to specified builder.
331      *
332      * @param builder Target builder
333      */
334     static final void narrowImplementedInterface(final GeneratedTypeBuilder builder) {
335         defineImplementedInterfaceMethod(builder, wildcardTypeFor(builder.getIdentifier()));
336     }
337
338     /**
339      * Add a default implementation of {@link DataContainer#implementedInterface()} to specified builder.
340      *
341      * @param builder Target builder
342      */
343     static final void defaultImplementedInterace(final GeneratedTypeBuilder builder) {
344         defineImplementedInterfaceMethod(builder, Type.of(builder)).setDefault(true);
345     }
346
347     static final <T extends EffectiveStatement<?, ?>> AbstractExplicitGenerator<T, ?> getChild(final Generator parent,
348             final Class<T> type) {
349         for (Generator child : parent) {
350             if (child instanceof AbstractExplicitGenerator) {
351                 @SuppressWarnings("unchecked")
352                 final AbstractExplicitGenerator<T, ?> explicit = (AbstractExplicitGenerator<T, ?>)child;
353                 if (type.isInstance(explicit.statement())) {
354                     return explicit;
355                 }
356             }
357         }
358         throw new IllegalStateException("Cannot find " + type + " in " + parent);
359     }
360
361     private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
362             final Type classType) {
363         final MethodSignatureBuilder ret = typeBuilder
364                 .addMethod(BindingMapping.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME)
365                 .setAccessModifier(AccessModifier.PUBLIC)
366                 .setReturnType(classType(classType));
367         ret.addAnnotation(OVERRIDE_ANNOTATION);
368         return ret;
369     }
370 }