2 * Copyright (c) 2018 Pantheon Technologies, 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.java.api.generator;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.encodeAngleBrackets;
14 import static org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.replaceAllIllegalChars;
16 import com.google.common.base.CharMatcher;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.collect.ImmutableSortedSet;
19 import java.lang.reflect.Method;
20 import java.util.AbstractMap;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.LinkedHashSet;
27 import java.util.List;
29 import java.util.NoSuchElementException;
30 import java.util.Objects;
31 import java.util.Optional;
33 import java.util.regex.Pattern;
34 import java.util.stream.Collectors;
35 import javax.annotation.processing.Generated;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.eclipse.xtext.xbase.lib.StringExtensions;
39 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
40 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
43 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
44 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
45 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
46 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
47 import org.opendaylight.mdsal.binding.model.api.Restrictions;
48 import org.opendaylight.mdsal.binding.model.api.Type;
49 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple;
50 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single;
51 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
52 import org.opendaylight.mdsal.binding.model.ri.Types;
53 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
54 import org.opendaylight.yangtools.yang.binding.Augmentable;
55 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
58 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
60 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
61 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
63 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
64 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
65 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
66 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
67 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter;
70 * Base Java file template. Contains a non-null type and imports which the generated code refers to.
72 class JavaFileTemplate {
74 * {@code java.lang.Class} as a JavaTypeName.
76 static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
78 * {@code java.lang.Deprecated} as a JavaTypeName.
80 static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
82 * {@code java.lang.IllegalArgumentException} as a JavaTypeName.
84 static final @NonNull JavaTypeName IAE = JavaTypeName.create(IllegalArgumentException.class);
86 * {@code java.lang.NullPointerException} as a JavaTypeName.
88 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
90 * {@code java.lang.NoSuchElementException} as a JavaTypeName.
92 static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
94 * {@code java.lang.Override} as a JavaTypeName.
96 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
98 * {@code java.lang.void} as a JavaTypeName.
100 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
102 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
104 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
107 * {@code java.util.Arrays} as a JavaTypeName.
109 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
111 * {@code java.util.HashMap} as a JavaTypeName.
113 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
115 * {@code java.util.List} as a JavaTypeName.
117 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
119 * {@code java.util.Map} as a JavaTypeName.
121 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
123 * {@code java.util.Objects} as a JavaTypeName.
125 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
127 * {@code java.util.regex.Pattern} as a JavaTypeName.
129 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
132 * {@code javax.annotation.processing.Generated} as a JavaTypeName.
134 static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
137 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
139 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
142 * {@code org.eclipse.jdt.annotation.NonNullByDefault} as a JavaTypeName.
144 static final @NonNull JavaTypeName NONNULL_BY_DEFAULT =
145 JavaTypeName.create("org.eclipse.jdt.annotation", "NonNullByDefault");
148 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
150 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
153 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
155 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
158 * {@code com.google.common.base.MoreObjects} as a JavaTypeName.
160 static final @NonNull JavaTypeName MOREOBJECTS = JavaTypeName.create(MoreObjects.class);
162 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
163 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
164 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
165 private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
166 .addIgnoredStatement(YangStmtMapping.CONTACT)
167 .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
168 .addIgnoredStatement(YangStmtMapping.REFERENCE)
169 .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
171 private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
172 private static final Type AUGMENTATION_RET_TYPE;
177 m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
178 } catch (NoSuchMethodException e) {
179 throw new ExceptionInInitializerError(e);
182 AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
185 private final AbstractJavaGeneratedType javaType;
186 private final GeneratedType type;
188 JavaFileTemplate(final @NonNull GeneratedType type) {
189 this(new TopLevelJavaGeneratedType(type), type);
192 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
193 this.javaType = requireNonNull(javaType);
194 this.type = requireNonNull(type);
197 final AbstractJavaGeneratedType javaType() {
201 final GeneratedType type() {
205 final String generateImportBlock() {
206 verify(javaType instanceof TopLevelJavaGeneratedType);
207 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
208 .collect(Collectors.joining());
211 final @NonNull String importedJavadocName(final @NonNull Type intype) {
212 return importedName(intype instanceof ParameterizedType parameterized ? parameterized.getRawType() : intype);
215 final @NonNull String importedName(final @NonNull Type intype) {
216 return javaType.getReferenceString(intype);
219 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
220 return javaType.getReferenceString(intype, annotation);
223 final @NonNull String importedName(final Class<?> cls) {
224 return importedName(Types.typeForClass(cls));
227 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
228 return javaType.getReferenceString(intype);
231 final @NonNull String importedNonNull(final @NonNull Type intype) {
232 return importedName(intype, importedName(NONNULL));
235 final @NonNull String importedNullable(final @NonNull Type intype) {
236 return importedName(intype, importedName(NULLABLE));
239 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
240 return fullyQualifiedName(intype, importedName(NONNULL));
243 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
244 return javaType.getFullyQualifiedReference(intype, annotation);
247 // Exposed for BuilderTemplate
248 boolean isLocalInnerClass(final JavaTypeName name) {
249 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
250 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
253 final CharSequence generateInnerClass(final GeneratedType innerClass) {
254 if (!(innerClass instanceof GeneratedTransferObject gto)) {
258 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
259 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
260 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
264 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
265 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
267 * @param property Generated property
268 * @return Imported class name
270 final String importedUtilClass(final GeneratedProperty property) {
271 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
274 final String generatedAnnotation() {
275 return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
279 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
280 * to the type, expressed as properties.
282 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
283 final Set<MethodSignature> methods = new LinkedHashSet<>();
284 final Type augmentType = createMethods(type, methods);
285 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
288 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
291 static final Restrictions restrictionsForSetter(final Type actualType) {
292 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
295 static final Restrictions getRestrictions(final Type type) {
296 if (type instanceof ConcreteType) {
297 return ((ConcreteType) type).getRestrictions();
299 if (type instanceof GeneratedTransferObject) {
300 return ((GeneratedTransferObject) type).getRestrictions();
306 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
308 * @param property Generated property
309 * @return The string used to clone the property, or an empty string
311 static final String cloneCall(final GeneratedProperty property) {
312 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
316 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
317 * and all the methods of the implemented interfaces.
319 * @returns set of method signature instances
321 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
322 methods.addAll(type.getMethodDefinitions());
323 return collectImplementedMethods(type, methods, type.getImplements());
327 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
328 * and recursively their implemented interfaces.
330 * @param methods set of method signatures
331 * @param implementedIfcs list of implemented interfaces
333 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
334 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
335 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
339 ParameterizedType augmentType = null;
340 for (Type implementedIfc : implementedIfcs) {
341 if (implementedIfc instanceof GeneratedType ifc && !(implementedIfc instanceof GeneratedTransferObject)) {
342 addImplMethods(methods, ifc);
344 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
345 if (t != null && augmentType == null) {
348 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
349 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
356 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
357 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
358 if (hasOverrideAnnotation(implMethod)) {
359 methods.add(implMethod);
361 final String implMethodName = implMethod.getName();
362 if (BindingMapping.isGetterMethodName(implMethodName)
363 && getterByName(methods, implMethodName).isEmpty()) {
365 methods.add(implMethod);
371 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
372 final String implMethodName) {
373 for (MethodSignature method : methods) {
374 final String methodName = method.getName();
375 if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
376 return Optional.of(method);
379 return Optional.empty();
382 protected static String propertyNameFromGetter(final MethodSignature getter) {
383 return propertyNameFromGetter(getter.getName());
386 protected static String propertyNameFromGetter(final String getterName) {
388 if (BindingMapping.isGetterMethodName(getterName)) {
389 prefix = BindingMapping.GETTER_PREFIX;
390 } else if (BindingMapping.isNonnullMethodName(getterName)) {
391 prefix = BindingMapping.NONNULL_PREFIX;
392 } else if (BindingMapping.isRequireMethodName(getterName)) {
393 prefix = BindingMapping.REQUIRE_PREFIX;
395 throw new IllegalArgumentException(getterName + " is not a getter");
397 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
401 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
403 * @param method Method to examine
404 * @return True if there is an override annotation
406 static boolean hasOverrideAnnotation(final MethodSignature method) {
407 for (final AnnotationType annotation : method.getAnnotations()) {
408 if (OVERRIDE.equals(annotation.getIdentifier())) {
415 final void appendSnippet(final StringBuilder sb, final GeneratedType genType) {
416 genType.getYangSourceDefinition().ifPresent(def -> {
419 if (def instanceof Single single) {
420 final DocumentedNode node = single.getNode();
423 .append("This class represents the following YANG schema fragment defined in module <b>")
424 .append(def.getModule().argument().getLocalName()).append("</b>\n")
426 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
429 if (node instanceof SchemaNode schema) {
430 // sb.append("The schema path to identify an instance is\n");
431 // appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
432 // sb.append("</i>\n");
434 if (hasBuilderClass(schema)) {
435 final String builderName = genType.getName() + BindingMapping.BUILDER_SUFFIX;
437 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
439 .append("@see ").append(builderName).append('\n');
440 if (node instanceof ListSchemaNode) {
441 final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
442 if (!keyDef.isEmpty()) {
443 sb.append("@see ").append(genType.getName()).append(BindingMapping.KEY_SUFFIX);
448 } else if (node instanceof AugmentEffectiveStatement) {
449 // Find target Augmentation<Foo> and reference Foo
450 final var augType = findAugmentationArgument(genType);
451 if (augType != null) {
453 .append("@see ").append(importedName(augType));
456 } else if (def instanceof Multiple multiple) {
457 sb.append("<pre>\n");
458 for (SchemaNode node : multiple.getNodes()) {
459 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
461 sb.append("</pre>\n");
466 private static @Nullable Type findAugmentationArgument(final GeneratedType genType) {
467 for (var implType : genType.getImplements()) {
468 if (implType instanceof ParameterizedType parameterized) {
469 final var augmentType = BindingTypes.extractAugmentable(parameterized);
470 if (augmentType != null) {
478 static String encodeJavadocSymbols(final String description) {
479 // FIXME: Use String.isBlank()?
480 return description == null || description.isEmpty() ? description
481 : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/");
484 private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
485 final DeclaredStatement<?> stmt) {
486 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
487 sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
491 // private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
492 // final List<QName> path) {
493 // if (!path.isEmpty()) {
494 // // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
495 // sb.append(module.argument().getLocalName());
496 // XMLNamespace currentNamespace = path.get(0).getNamespace();
498 // for (QName pathElement : path) {
499 // final XMLNamespace elementNamespace = pathElement.getNamespace();
500 // if (!elementNamespace.equals(currentNamespace)) {
501 // sb.append(pathElement);
502 // currentNamespace = elementNamespace;
504 // sb.append(pathElement.getLocalName());
510 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
511 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
512 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
515 private static boolean isSameProperty(final String getterName1, final String getterName2) {
516 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
520 * Creates set of generated property instances from getter <code>methods</code>.
522 * @param methods set of method signature instances which should be transformed to list of properties
523 * @return set of generated property instances which represents the getter <code>methods</code>
525 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
526 if (methods == null || methods.isEmpty()) {
527 return Collections.emptySet();
529 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
530 for (MethodSignature m : methods) {
531 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
532 if (createdField != null) {
533 result.add(createdField);
540 * Creates generated property instance from the getter <code>method</code> name and return type.
542 * @param method method signature from which is the method name and return type obtained
543 * @return generated property instance for the getter <code>method</code>
544 * @throws IllegalArgumentException <ul>
545 * <li>if the {@code method} equals {@code null}</li>
546 * <li>if the name of the {@code method} equals {@code null}</li>
547 * <li>if the name of the {@code method} is empty</li>
548 * <li>if the return type of the {@code method} equals {@code null}</li>
551 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
552 checkArgument(method != null);
553 checkArgument(method.getReturnType() != null);
554 checkArgument(method.getName() != null);
555 checkArgument(!method.getName().isEmpty());
556 if (method.isDefault()) {
559 if (!BindingMapping.isGetterMethodName(method.getName())) {
563 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
564 return new BuilderGeneratedProperty(fieldName, method);