2 * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.generator.impl.reactor;
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;
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;
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.
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.
57 * Overall the tree layout guides the allocation of Java package and top-level class namespaces.
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);
63 private final AbstractCompositeGenerator<?, ?> parent;
65 private Optional<Member> member;
66 private GeneratorResult result;
67 private JavaTypeName typeName;
68 private String javaPackage;
74 Generator(final AbstractCompositeGenerator<?, ?> parent) {
75 this.parent = requireNonNull(parent);
78 public final @NonNull Optional<GeneratedType> generatedType() {
79 return Optional.ofNullable(result.generatedType());
82 public @NonNull List<GeneratedType> auxiliaryGeneratedTypes() {
87 public Iterator<Generator> iterator() {
88 return Collections.emptyIterator();
92 * Return the {@link AbstractCompositeGenerator} inside which this generator is defined. It is illegal to call this
93 * method on a {@link ModuleGenerator}.
95 * @return Parent generator
97 final @NonNull AbstractCompositeGenerator<?, ?> getParent() {
98 return verifyNotNull(parent, "No parent for %s", this);
106 * Return the namespace of this statement.
108 * @return Corresponding namespace
109 * @throws UnsupportedOperationException if this node does not have a corresponding namespace
111 abstract @NonNull StatementNamespace namespace();
113 @NonNull ModuleGenerator currentModule() {
114 return getParent().currentModule();
118 * Push this statement into a {@link SchemaInferenceStack} so that the stack contains a resolvable {@code data tree}
121 * @param inferenceStack Target inference stack
123 abstract void pushToInference(@NonNull SchemaInferenceStack inferenceStack);
125 abstract @NonNull ClassPlacement classPlacement();
127 final @NonNull Member getMember() {
128 return verifyNotNull(ensureMember(), "No member for %s", this);
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()));
138 return member.orElse(null);
141 @NonNull CollisionDomain parentDomain() {
142 return getParent().domain();
145 abstract @NonNull Member createMember(@NonNull CollisionDomain domain);
148 * Create the type associated with this builder. This method idempotent.
150 * @param builderFactory Factory for {@link TypeBuilder}s
151 * @throws NullPointerException if {@code builderFactory} is {@code null}
153 final void ensureType(final TypeBuilderFactory builderFactory) {
154 if (result != null) {
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)));
164 for (Generator child : this) {
165 child.ensureType(builderFactory);
169 @NonNull GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
170 return verifyNotNull(tryGeneratedType(builderFactory), "No type generated for %s", this);
173 final @Nullable GeneratedType tryGeneratedType(final TypeBuilderFactory builderFactory) {
174 ensureType(builderFactory);
175 return result.generatedType();
178 final @Nullable GeneratedType enclosedType(final TypeBuilderFactory builderFactory) {
179 ensureType(builderFactory);
180 return result.enclosedType();
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.
187 * @param builderFactory Factory for {@link TypeBuilder}s
189 abstract @NonNull GeneratedType createTypeImpl(@NonNull TypeBuilderFactory builderFactory);
191 final @NonNull String assignedName() {
192 return getMember().currentClass();
195 final @NonNull String javaPackage() {
196 String local = javaPackage;
198 javaPackage = local = createJavaPackage();
203 @NonNull String createJavaPackage() {
204 final String parentPackage = getPackageParent().javaPackage();
205 final String myPackage = getMember().currentPackage();
206 return Naming.normalizePackageName(parentPackage + '.' + myPackage);
209 final @NonNull JavaTypeName typeName() {
210 JavaTypeName local = typeName;
212 typeName = local = createTypeName();
217 @NonNull JavaTypeName createTypeName() {
218 return JavaTypeName.create(getPackageParent().javaPackage(), assignedName());
221 @NonNull AbstractCompositeGenerator<?, ?> getPackageParent() {
226 public final String toString() {
227 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
230 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
234 final void addImplementsChildOf(final GeneratedTypeBuilder builder) {
235 AbstractCompositeGenerator<?, ?> ancestor = getParent();
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();
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;
253 builder.addImplementsType(BindingTypes.childOf(Type.of(ancestor.typeName())));
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()}.
260 * @param builder Target builder
262 static final void addConcreteInterfaceMethods(final GeneratedTypeBuilder builder) {
263 defaultImplementedInterace(builder);
265 builder.addMethod(Naming.BINDING_HASHCODE_NAME)
266 .setAccessModifier(AccessModifier.PUBLIC)
268 .setReturnType(primitiveIntType());
269 builder.addMethod(Naming.BINDING_EQUALS_NAME)
270 .setAccessModifier(AccessModifier.PUBLIC)
272 .setReturnType(primitiveBooleanType());
273 builder.addMethod(Naming.BINDING_TO_STRING_NAME)
274 .setAccessModifier(AccessModifier.PUBLIC)
276 .setReturnType(STRING);
279 static final void annotateDeprecatedIfNecessary(final EffectiveStatement<?, ?> stmt,
280 final AnnotableTypeBuilder builder) {
281 if (stmt instanceof WithStatus withStatus) {
282 annotateDeprecatedIfNecessary(withStatus, builder);
286 static final void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
287 switch (node.getStatus()) {
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");
295 default -> throw new IllegalStateException("Unhandled status in " + node);
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);
311 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
314 * @param builder transfer object which needs to be made serializable
316 static final void makeSerializable(final GeneratedTOBuilder builder) {
317 builder.addImplementsType(Types.serializableType());
318 addSerialVersionUID(builder);
321 static final void addSerialVersionUID(final GeneratedTOBuilder gto) {
322 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
323 prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
328 * Add a {@link DataContainer#implementedInterface()} declaration with a narrower return type to specified builder.
330 * @param builder Target builder
332 static final void narrowImplementedInterface(final GeneratedTypeBuilder builder) {
333 defineImplementedInterfaceMethod(builder, wildcardTypeFor(builder.getIdentifier()));
337 * Add a default implementation of {@link DataContainer#implementedInterface()} to specified builder.
339 * @param builder Target builder
341 static final void defaultImplementedInterace(final GeneratedTypeBuilder builder) {
342 defineImplementedInterfaceMethod(builder, Type.of(builder)).setDefault(true);
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())) {
356 throw new IllegalStateException("Cannot find " + type + " in " + parent);
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);