Rehost BindingMapping in yang.binding.contract.Naming
[mdsal.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.yangtools.yang.binding.DataContainer;
40 import org.opendaylight.yangtools.yang.binding.contract.Naming;
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     abstract @NonNull StatementNamespace namespace();
112
113     @NonNull ModuleGenerator currentModule() {
114         return getParent().currentModule();
115     }
116
117     /**
118      * Push this statement into a {@link SchemaInferenceStack} so that the stack contains a resolvable {@code data tree}
119      * hierarchy.
120      *
121      * @param inferenceStack Target inference stack
122      */
123     abstract void pushToInference(@NonNull SchemaInferenceStack inferenceStack);
124
125     abstract @NonNull ClassPlacement classPlacement();
126
127     final @NonNull Member getMember() {
128         return verifyNotNull(ensureMember(), "No member for %s", this);
129     }
130
131     final Member ensureMember() {
132         if (member == null) {
133             member = switch (classPlacement()) {
134                 case NONE -> Optional.empty();
135                 case MEMBER, PHANTOM, TOP_LEVEL -> Optional.of(createMember(parentDomain()));
136             };
137         }
138         return member.orElse(null);
139     }
140
141     @NonNull CollisionDomain parentDomain() {
142         return getParent().domain();
143     }
144
145     abstract @NonNull Member createMember(@NonNull CollisionDomain domain);
146
147     /**
148      * Create the type associated with this builder. This method idempotent.
149      *
150      * @param builderFactory Factory for {@link TypeBuilder}s
151      * @throws NullPointerException if {@code builderFactory} is {@code null}
152      */
153     final void ensureType(final TypeBuilderFactory builderFactory) {
154         if (result != null) {
155             return;
156         }
157
158         result = switch (classPlacement()) {
159             case NONE, PHANTOM -> GeneratorResult.empty();
160             case MEMBER -> GeneratorResult.member(createTypeImpl(requireNonNull(builderFactory)));
161             case TOP_LEVEL -> GeneratorResult.toplevel(createTypeImpl(requireNonNull(builderFactory)));
162         };
163
164         for (Generator child : this) {
165             child.ensureType(builderFactory);
166         }
167     }
168
169     @NonNull GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
170         return verifyNotNull(tryGeneratedType(builderFactory), "No type generated for %s", this);
171     }
172
173     final @Nullable GeneratedType tryGeneratedType(final TypeBuilderFactory builderFactory) {
174         ensureType(builderFactory);
175         return result.generatedType();
176     }
177
178     final @Nullable GeneratedType enclosedType(final TypeBuilderFactory builderFactory) {
179         ensureType(builderFactory);
180         return result.enclosedType();
181     }
182
183     /**
184      * Create the type associated with this builder, as per {@link #ensureType(TypeBuilderFactory)} contract. This
185      * method is guaranteed to be called at most once.
186      *
187      * @param builderFactory Factory for {@link TypeBuilder}s
188      */
189     abstract @NonNull GeneratedType createTypeImpl(@NonNull TypeBuilderFactory builderFactory);
190
191     final @NonNull String assignedName() {
192         return getMember().currentClass();
193     }
194
195     final @NonNull String javaPackage() {
196         String local = javaPackage;
197         if (local == null) {
198             javaPackage = local = createJavaPackage();
199         }
200         return local;
201     }
202
203     @NonNull String createJavaPackage() {
204         final String parentPackage = getPackageParent().javaPackage();
205         final String myPackage = getMember().currentPackage();
206         return Naming.normalizePackageName(parentPackage + '.' + myPackage);
207     }
208
209     final @NonNull JavaTypeName typeName() {
210         JavaTypeName local = typeName;
211         if (local == null) {
212             typeName = local = createTypeName();
213         }
214         return local;
215     }
216
217     @NonNull JavaTypeName createTypeName() {
218         return JavaTypeName.create(getPackageParent().javaPackage(), assignedName());
219     }
220
221     @NonNull AbstractCompositeGenerator<?, ?> getPackageParent() {
222         return getParent();
223     }
224
225     @Override
226     public final String toString() {
227         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
228     }
229
230     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
231         return helper;
232     }
233
234     final void addImplementsChildOf(final GeneratedTypeBuilder builder) {
235         AbstractCompositeGenerator<?, ?> ancestor = getParent();
236         while (true) {
237             // choice/case hierarchy does not factor into 'ChildOf' hierarchy, hence we need to skip them
238             if (ancestor instanceof CaseGenerator || ancestor instanceof ChoiceGenerator) {
239                 ancestor = ancestor.getParent();
240                 continue;
241             }
242
243             // if we into a choice we need to follow the hierararchy of that choice
244             if (ancestor instanceof AbstractAugmentGenerator augment
245                 && augment.targetGenerator() instanceof ChoiceGenerator targetChoice) {
246                 ancestor = targetChoice;
247                 continue;
248             }
249
250             break;
251         }
252
253         builder.addImplementsType(BindingTypes.childOf(Type.of(ancestor.typeName())));
254     }
255
256     /**
257      * Add common methods implemented in a generated type. This includes {@link DataContainer#implementedInterface()} as
258      * well has {@code bindingHashCode()}, {@code bindingEquals()} and {@code bindingToString()}.
259      *
260      * @param builder Target builder
261      */
262     static final void addConcreteInterfaceMethods(final GeneratedTypeBuilder builder) {
263         defaultImplementedInterace(builder);
264
265         builder.addMethod(Naming.BINDING_HASHCODE_NAME)
266             .setAccessModifier(AccessModifier.PUBLIC)
267             .setStatic(true)
268             .setReturnType(primitiveIntType());
269         builder.addMethod(Naming.BINDING_EQUALS_NAME)
270             .setAccessModifier(AccessModifier.PUBLIC)
271             .setStatic(true)
272             .setReturnType(primitiveBooleanType());
273         builder.addMethod(Naming.BINDING_TO_STRING_NAME)
274             .setAccessModifier(AccessModifier.PUBLIC)
275             .setStatic(true)
276             .setReturnType(STRING);
277     }
278
279     static final void annotateDeprecatedIfNecessary(final EffectiveStatement<?, ?> stmt,
280             final AnnotableTypeBuilder builder) {
281         if (stmt instanceof WithStatus withStatus) {
282             annotateDeprecatedIfNecessary(withStatus, builder);
283         }
284     }
285
286     static final void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
287         switch (node.getStatus()) {
288             case DEPRECATED ->
289                 // FIXME: we really want to use a pre-made annotation
290                 builder.addAnnotation(DEPRECATED_ANNOTATION);
291             case OBSOLETE -> builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
292             case CURRENT -> {
293                 // No-op
294             }
295             default -> throw new IllegalStateException("Unhandled status in " + node);
296         }
297     }
298
299     static final void addUnits(final GeneratedTOBuilder builder, final TypeDefinition<?> typedef) {
300         typedef.getUnits().ifPresent(units -> {
301             if (!units.isEmpty()) {
302                 builder.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
303                 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
304                 prop.setReturnType(Types.STRING);
305                 builder.addToStringProperty(prop);
306             }
307         });
308     }
309
310     /**
311      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
312      * property.
313      *
314      * @param builder transfer object which needs to be made serializable
315      */
316     static final void makeSerializable(final GeneratedTOBuilder builder) {
317         builder.addImplementsType(Types.serializableType());
318         addSerialVersionUID(builder);
319     }
320
321     static final void addSerialVersionUID(final GeneratedTOBuilder gto) {
322         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
323         prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
324         gto.setSUID(prop);
325     }
326
327     /**
328      * Add a {@link DataContainer#implementedInterface()} declaration with a narrower return type to specified builder.
329      *
330      * @param builder Target builder
331      */
332     static final void narrowImplementedInterface(final GeneratedTypeBuilder builder) {
333         defineImplementedInterfaceMethod(builder, wildcardTypeFor(builder.getIdentifier()));
334     }
335
336     /**
337      * Add a default implementation of {@link DataContainer#implementedInterface()} to specified builder.
338      *
339      * @param builder Target builder
340      */
341     static final void defaultImplementedInterace(final GeneratedTypeBuilder builder) {
342         defineImplementedInterfaceMethod(builder, Type.of(builder)).setDefault(true);
343     }
344
345     static final <T extends EffectiveStatement<?, ?>> AbstractExplicitGenerator<T, ?> getChild(final Generator parent,
346             final Class<T> type) {
347         for (Generator child : parent) {
348             if (child instanceof AbstractExplicitGenerator) {
349                 @SuppressWarnings("unchecked")
350                 final AbstractExplicitGenerator<T, ?> explicit = (AbstractExplicitGenerator<T, ?>)child;
351                 if (type.isInstance(explicit.statement())) {
352                     return explicit;
353                 }
354             }
355         }
356         throw new IllegalStateException("Cannot find " + type + " in " + parent);
357     }
358
359     private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
360             final Type classType) {
361         final MethodSignatureBuilder ret = typeBuilder
362                 .addMethod(Naming.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME)
363                 .setAccessModifier(AccessModifier.PUBLIC)
364                 .setReturnType(classType(classType));
365         ret.addAnnotation(OVERRIDE_ANNOTATION);
366         return ret;
367     }
368 }