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.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;
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 @NonNull StatementNamespace namespace() {
112 return StatementNamespace.DEFAULT;
115 @NonNull ModuleGenerator currentModule() {
116 return getParent().currentModule();
120 * Push this statement into a {@link SchemaInferenceStack} so that the stack contains a resolvable {@code data tree}
123 * @param inferenceStack Target inference stack
125 abstract void pushToInference(@NonNull SchemaInferenceStack inferenceStack);
127 abstract @NonNull ClassPlacement classPlacement();
129 final @NonNull Member getMember() {
130 return verifyNotNull(ensureMember(), "No member for %s", this);
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()));
140 return member.orElse(null);
143 @NonNull CollisionDomain parentDomain() {
144 return getParent().domain();
147 abstract @NonNull Member createMember(@NonNull CollisionDomain domain);
150 * Create the type associated with this builder. This method idempotent.
152 * @param builderFactory Factory for {@link TypeBuilder}s
153 * @throws NullPointerException if {@code builderFactory} is {@code null}
155 final void ensureType(final TypeBuilderFactory builderFactory) {
156 if (result != null) {
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)));
166 for (Generator child : this) {
167 child.ensureType(builderFactory);
171 @NonNull GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
172 return verifyNotNull(tryGeneratedType(builderFactory), "No type generated for %s", this);
175 final @Nullable GeneratedType tryGeneratedType(final TypeBuilderFactory builderFactory) {
176 ensureType(builderFactory);
177 return result.generatedType();
180 final @Nullable GeneratedType enclosedType(final TypeBuilderFactory builderFactory) {
181 ensureType(builderFactory);
182 return result.enclosedType();
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.
189 * @param builderFactory Factory for {@link TypeBuilder}s
191 abstract @NonNull GeneratedType createTypeImpl(@NonNull TypeBuilderFactory builderFactory);
193 final @NonNull String assignedName() {
194 return getMember().currentClass();
197 final @NonNull String javaPackage() {
198 String local = javaPackage;
200 javaPackage = local = createJavaPackage();
205 @NonNull String createJavaPackage() {
206 final String parentPackage = getPackageParent().javaPackage();
207 final String myPackage = getMember().currentPackage();
208 return BindingMapping.normalizePackageName(parentPackage + '.' + myPackage);
211 final @NonNull JavaTypeName typeName() {
212 JavaTypeName local = typeName;
214 typeName = local = createTypeName();
219 @NonNull JavaTypeName createTypeName() {
220 return JavaTypeName.create(getPackageParent().javaPackage(), assignedName());
223 @NonNull AbstractCompositeGenerator<?, ?> getPackageParent() {
228 public final String toString() {
229 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
232 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
236 final void addImplementsChildOf(final GeneratedTypeBuilder builder) {
237 AbstractCompositeGenerator<?, ?> ancestor = getParent();
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();
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;
255 builder.addImplementsType(BindingTypes.childOf(Type.of(ancestor.typeName())));
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()}.
262 * @param builder Target builder
264 static final void addConcreteInterfaceMethods(final GeneratedTypeBuilder builder) {
265 defaultImplementedInterace(builder);
267 builder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
268 .setAccessModifier(AccessModifier.PUBLIC)
270 .setReturnType(primitiveIntType());
271 builder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
272 .setAccessModifier(AccessModifier.PUBLIC)
274 .setReturnType(primitiveBooleanType());
275 builder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
276 .setAccessModifier(AccessModifier.PUBLIC)
278 .setReturnType(STRING);
281 static final void annotateDeprecatedIfNecessary(final EffectiveStatement<?, ?> stmt,
282 final AnnotableTypeBuilder builder) {
283 if (stmt instanceof WithStatus withStatus) {
284 annotateDeprecatedIfNecessary(withStatus, builder);
288 static final void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
289 switch (node.getStatus()) {
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");
297 default -> throw new IllegalStateException("Unhandled status in " + node);
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);
313 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
316 * @param builder transfer object which needs to be made serializable
318 static final void makeSerializable(final GeneratedTOBuilder builder) {
319 builder.addImplementsType(Types.serializableType());
320 addSerialVersionUID(builder);
323 static final void addSerialVersionUID(final GeneratedTOBuilder gto) {
324 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
325 prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
330 * Add a {@link DataContainer#implementedInterface()} declaration with a narrower return type to specified builder.
332 * @param builder Target builder
334 static final void narrowImplementedInterface(final GeneratedTypeBuilder builder) {
335 defineImplementedInterfaceMethod(builder, wildcardTypeFor(builder.getIdentifier()));
339 * Add a default implementation of {@link DataContainer#implementedInterface()} to specified builder.
341 * @param builder Target builder
343 static final void defaultImplementedInterace(final GeneratedTypeBuilder builder) {
344 defineImplementedInterfaceMethod(builder, Type.of(builder)).setDefault(true);
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())) {
358 throw new IllegalStateException("Cannot find " + type + " in " + parent);
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);