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.util.Types.STRING;
13 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
14 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveBooleanType;
15 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveIntType;
16 import static org.opendaylight.mdsal.binding.model.util.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.YangSourceDefinition;
32 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
33 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
36 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
37 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
38 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
39 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
40 import org.opendaylight.mdsal.binding.model.util.TypeComments;
41 import org.opendaylight.mdsal.binding.model.util.Types;
42 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
43 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
46 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
50 import org.opendaylight.yangtools.yang.model.ri.type.TypeBuilder;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
54 * A single node in generator tree. Each node will eventually resolve to a generated Java class. Each node also can have
55 * a number of children, which are generators corresponding to the YANG subtree of this node.
57 public abstract class Generator implements Iterable<Generator> {
58 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
59 static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
61 private final AbstractCompositeGenerator<?> parent;
63 private Optional<Member> member;
64 private GeneratorResult result;
65 private JavaTypeName typeName;
66 private String javaPackage;
72 Generator(final AbstractCompositeGenerator<?> parent) {
73 this.parent = requireNonNull(parent);
76 public final @NonNull Optional<GeneratedType> generatedType() {
77 return Optional.ofNullable(result.generatedType());
80 public @NonNull List<GeneratedType> auxiliaryGeneratedTypes() {
85 public Iterator<Generator> iterator() {
86 return Collections.emptyIterator();
90 * Return the {@link AbstractCompositeGenerator} inside which this generator is defined. It is illegal to call this
91 * method on a {@link ModuleGenerator}.
93 * @return Parent generator
95 final @NonNull AbstractCompositeGenerator<?> getParent() {
96 return verifyNotNull(parent, "No parent for %s", this);
103 @Nullable Generator findGenerator(final EffectiveStatement<?, ?> stmt) {
107 final @NonNull Generator getGenerator(final EffectiveStatement<?, ?> stmt) {
108 return verifyNotNull(findGenerator(stmt), "Cannot match statement %s in %s", stmt, this);
112 * Return the namespace of this statement.
114 * @return Corresponding namespace
115 * @throws UnsupportedOperationException if this node does not have a corresponding namespace
117 @NonNull StatementNamespace namespace() {
118 return StatementNamespace.DEFAULT;
121 @NonNull ModuleGenerator currentModule() {
122 return getParent().currentModule();
126 * Push this statement into a {@link SchemaInferenceStack} so that the stack contains a resolvable {@code data tree}
129 * @param inferenceStack Target inference stack
131 abstract void pushToInference(@NonNull SchemaInferenceStack inferenceStack);
133 abstract @NonNull ClassPlacement classPlacement();
135 final @NonNull Member getMember() {
136 return verifyNotNull(ensureMember(), "No member for %s", this);
139 final Member ensureMember() {
140 if (member == null) {
141 final ClassPlacement placement = classPlacement();
144 member = Optional.empty();
149 member = Optional.of(createMember(parentDomain()));
152 throw new IllegalStateException("Unhandled placement " + placement);
155 return member.orElse(null);
158 @NonNull CollisionDomain parentDomain() {
159 return getParent().domain();
162 abstract @NonNull Member createMember(@NonNull CollisionDomain domain);
165 * Create the type associated with this builder. This method idempotent.
167 * @param builderFactory Factory for {@link TypeBuilder}s
168 * @throws NullPointerException if {@code builderFactory} is {@code null}
170 final void ensureType(final TypeBuilderFactory builderFactory) {
171 if (result != null) {
175 final ClassPlacement placement = classPlacement();
179 result = GeneratorResult.empty();
182 result = GeneratorResult.member(createTypeImpl(requireNonNull(builderFactory)));
185 result = GeneratorResult.toplevel(createTypeImpl(requireNonNull(builderFactory)));
188 throw new IllegalStateException("Unhandled placement " + placement);
191 for (Generator child : this) {
192 child.ensureType(builderFactory);
196 @NonNull GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
197 return verifyNotNull(tryGeneratedType(builderFactory), "No type generated for %s", this);
200 final @Nullable GeneratedType tryGeneratedType(final TypeBuilderFactory builderFactory) {
201 ensureType(builderFactory);
202 return result.generatedType();
205 final @Nullable GeneratedType enclosedType(final TypeBuilderFactory builderFactory) {
206 ensureType(builderFactory);
207 return result.enclosedType();
211 * Create the type associated with this builder, as per {@link #ensureType(TypeBuilderFactory)} contract. This
212 * method is guaranteed to be called at most once.
214 * @param builderFactory Factory for {@link TypeBuilder}s
216 abstract @NonNull GeneratedType createTypeImpl(@NonNull TypeBuilderFactory builderFactory);
218 final @NonNull String assignedName() {
219 return getMember().currentClass();
222 final @NonNull String javaPackage() {
223 String local = javaPackage;
225 javaPackage = local = createJavaPackage();
230 @NonNull String createJavaPackage() {
231 final String parentPackage = getPackageParent().javaPackage();
232 final String myPackage = getMember().currentPackage();
233 return BindingMapping.normalizePackageName(parentPackage + '.' + myPackage);
236 final @NonNull JavaTypeName typeName() {
237 JavaTypeName local = typeName;
239 typeName = local = createTypeName();
244 @NonNull JavaTypeName createTypeName() {
245 return JavaTypeName.create(getPackageParent().javaPackage(), assignedName());
248 @NonNull AbstractCompositeGenerator<?> getPackageParent() {
253 public final String toString() {
254 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
257 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
261 final void addImplementsChildOf(final GeneratedTypeBuilder builder) {
262 AbstractCompositeGenerator<?> ancestor = getParent();
264 // choice/case hierarchy does not factor into 'ChildOf' hierarchy, hence we need to skip them
265 if (ancestor instanceof CaseGenerator || ancestor instanceof ChoiceGenerator) {
266 ancestor = ancestor.getParent();
270 // if we into a choice we need to follow the hierararchy of that choice
271 if (ancestor instanceof AbstractAugmentGenerator) {
272 final AbstractCompositeGenerator<?> target = ((AbstractAugmentGenerator) ancestor).targetGenerator();
273 if (target instanceof ChoiceGenerator) {
282 builder.addImplementsType(BindingTypes.childOf(Type.of(ancestor.typeName())));
286 * Add common methods implemented in a generated type. This includes {@link DataContainer#implementedInterface()} as
287 * well has {@code bindingHashCode()}, {@code bindingEquals()} and {@code bindingToString()}.
289 * @param builder Target builder
291 static final void addConcreteInterfaceMethods(final GeneratedTypeBuilder builder) {
292 defaultImplementedInterace(builder);
294 builder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
295 .setAccessModifier(AccessModifier.PUBLIC)
297 .setReturnType(primitiveIntType());
298 builder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
299 .setAccessModifier(AccessModifier.PUBLIC)
301 .setReturnType(primitiveBooleanType());
302 builder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
303 .setAccessModifier(AccessModifier.PUBLIC)
305 .setReturnType(STRING);
308 static final void annotateDeprecatedIfNecessary(final EffectiveStatement<?, ?> stmt,
309 final AnnotableTypeBuilder builder) {
310 if (stmt instanceof WithStatus) {
311 annotateDeprecatedIfNecessary((WithStatus) stmt, builder);
315 static final void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
316 switch (node.getStatus()) {
318 // FIXME: we really want to use a pre-made annotation
319 builder.addAnnotation(DEPRECATED_ANNOTATION);
322 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
328 throw new IllegalStateException("Unhandled status in " + node);
332 static final void addCodegenInformation(final EffectiveStatement<?, ?> stmt,
333 final GeneratedTypeBuilderBase<?> builder) {
334 if (stmt instanceof DocumentedNode) {
335 addCodegenInformation((DocumentedNode) stmt, builder);
339 static final void addCodegenInformation(final DocumentedNode node, final GeneratedTypeBuilderBase<?> builder) {
340 node.getDescription().map(BindingGeneratorUtil::encodeAngleBrackets).ifPresent(builder::setDescription);
341 node.getReference().ifPresent(builder::setReference);
344 static final void addCodegenInformation(final ModuleGenerator module, final EffectiveStatement<?, ?> stmt,
345 final GeneratedTypeBuilderBase<?> builder) {
346 if (stmt instanceof DocumentedNode) {
347 final DocumentedNode node = (DocumentedNode) stmt;
348 TypeComments.description(node).ifPresent(builder::addComment);
349 node.getDescription().ifPresent(builder::setDescription);
350 node.getReference().ifPresent(builder::setReference);
352 if (stmt instanceof SchemaNode) {
353 YangSourceDefinition.of(module.statement(), (SchemaNode) stmt).ifPresent(builder::setYangSourceDefinition);
357 static final void addUnits(final GeneratedTOBuilder builder, final TypeDefinition<?> typedef) {
358 typedef.getUnits().ifPresent(units -> {
359 if (!units.isEmpty()) {
360 builder.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
361 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
362 prop.setReturnType(Types.STRING);
363 builder.addToStringProperty(prop);
369 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
372 * @param builder transfer object which needs to be made serializable
374 static final void makeSerializable(final GeneratedTOBuilder builder) {
375 builder.addImplementsType(Types.serializableType());
376 addSerialVersionUID(builder);
379 static final void addSerialVersionUID(final GeneratedTOBuilder gto) {
380 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
381 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
386 * Add a {@link DataContainer#implementedInterface()} declaration with a narrower return type to specified builder.
388 * @param builder Target builder
390 static final void narrowImplementedInterface(final GeneratedTypeBuilder builder) {
391 defineImplementedInterfaceMethod(builder, wildcardTypeFor(builder.getIdentifier()));
395 * Add a default implementation of {@link DataContainer#implementedInterface()} to specified builder.
397 * @param builder Target builder
399 static final void defaultImplementedInterace(final GeneratedTypeBuilder builder) {
400 defineImplementedInterfaceMethod(builder, Type.of(builder)).setDefault(true);
403 static final <T extends EffectiveStatement<?, ?>> AbstractExplicitGenerator<T> getChild(final Generator parent,
404 final Class<T> type) {
405 for (Generator child : parent) {
406 if (child instanceof AbstractExplicitGenerator) {
407 @SuppressWarnings("unchecked")
408 final AbstractExplicitGenerator<T> explicit = (AbstractExplicitGenerator<T>)child;
409 if (type.isInstance(explicit.statement())) {
414 throw new IllegalStateException("Cannot find " + type + " in " + parent);
417 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
418 final Type classType) {
419 final MethodSignatureBuilder ret = typeBuilder
420 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
421 .setAccessModifier(AccessModifier.PUBLIC)
422 .setReturnType(classType(classType));
423 ret.addAnnotation(OVERRIDE_ANNOTATION);