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.xtext.xbase.lib.StringExtensions;
38 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
39 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
43 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
44 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
45 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
46 import org.opendaylight.mdsal.binding.model.api.Restrictions;
47 import org.opendaylight.mdsal.binding.model.api.Type;
48 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple;
49 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single;
50 import org.opendaylight.mdsal.binding.model.ri.Types;
51 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
52 import org.opendaylight.yangtools.yang.binding.Augmentable;
53 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
54 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
56 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
61 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
62 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
63 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
64 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter;
67 * Base Java file template. Contains a non-null type and imports which the generated code refers to.
69 class JavaFileTemplate {
71 * {@code java.lang.Class} as a JavaTypeName.
73 static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
75 * {@code java.lang.Deprecated} as a JavaTypeName.
77 static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
79 * {@code java.lang.IllegalArgumentException} as a JavaTypeName.
81 static final @NonNull JavaTypeName IAE = JavaTypeName.create(IllegalArgumentException.class);
83 * {@code java.lang.NullPointerException} as a JavaTypeName.
85 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
87 * {@code java.lang.NoSuchElementException} as a JavaTypeName.
89 static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
91 * {@code java.lang.Override} as a JavaTypeName.
93 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
95 * {@code java.lang.void} as a JavaTypeName.
97 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
99 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
101 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
104 * {@code java.util.Arrays} as a JavaTypeName.
106 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
108 * {@code java.util.HashMap} as a JavaTypeName.
110 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
112 * {@code java.util.List} as a JavaTypeName.
114 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
116 * {@code java.util.Map} as a JavaTypeName.
118 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
120 * {@code java.util.Objects} as a JavaTypeName.
122 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
124 * {@code java.util.regex.Pattern} as a JavaTypeName.
126 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
129 * {@code javax.annotation.processing.Generated} as a JavaTypeName.
131 static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
134 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
136 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
138 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
140 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
143 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
145 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
148 * {@code com.google.common.base.MoreObjects} as a JavaTypeName.
150 static final @NonNull JavaTypeName MOREOBJECTS = JavaTypeName.create(MoreObjects.class);
152 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
153 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
154 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
155 private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
156 .addIgnoredStatement(YangStmtMapping.CONTACT)
157 .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
158 .addIgnoredStatement(YangStmtMapping.REFERENCE)
159 .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
161 private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
162 private static final Type AUGMENTATION_RET_TYPE;
167 m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
168 } catch (NoSuchMethodException e) {
169 throw new ExceptionInInitializerError(e);
172 AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
175 private final AbstractJavaGeneratedType javaType;
176 private final GeneratedType type;
178 JavaFileTemplate(final @NonNull GeneratedType type) {
179 this(new TopLevelJavaGeneratedType(type), type);
182 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
183 this.javaType = requireNonNull(javaType);
184 this.type = requireNonNull(type);
187 final AbstractJavaGeneratedType javaType() {
191 final GeneratedType type() {
195 final String generateImportBlock() {
196 verify(javaType instanceof TopLevelJavaGeneratedType);
197 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
198 .collect(Collectors.joining());
201 final @NonNull String importedJavadocName(final @NonNull Type intype) {
202 return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
205 final @NonNull String importedName(final @NonNull Type intype) {
206 return javaType.getReferenceString(intype);
209 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
210 return javaType.getReferenceString(intype, annotation);
213 final @NonNull String importedName(final Class<?> cls) {
214 return importedName(Types.typeForClass(cls));
217 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
218 return javaType.getReferenceString(intype);
221 final @NonNull String importedNonNull(final @NonNull Type intype) {
222 return importedName(intype, importedName(NONNULL));
225 final @NonNull String importedNullable(final @NonNull Type intype) {
226 return importedName(intype, importedName(NULLABLE));
229 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
230 return fullyQualifiedName(intype, importedName(NONNULL));
233 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
234 return javaType.getFullyQualifiedReference(intype, annotation);
237 // Exposed for BuilderTemplate
238 boolean isLocalInnerClass(final JavaTypeName name) {
239 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
240 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
243 final CharSequence generateInnerClass(final GeneratedType innerClass) {
244 if (!(innerClass instanceof GeneratedTransferObject)) {
248 final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
249 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
250 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
251 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
255 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
256 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
258 * @param property Generated property
259 * @return Imported class name
261 final String importedUtilClass(final GeneratedProperty property) {
262 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
265 final String generatedAnnotation() {
266 return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
270 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
271 * to the type, expressed as properties.
273 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
274 final Set<MethodSignature> methods = new LinkedHashSet<>();
275 final Type augmentType = createMethods(type, methods);
276 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
279 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
282 static final Restrictions restrictionsForSetter(final Type actualType) {
283 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
286 static final Restrictions getRestrictions(final Type type) {
287 if (type instanceof ConcreteType) {
288 return ((ConcreteType) type).getRestrictions();
290 if (type instanceof GeneratedTransferObject) {
291 return ((GeneratedTransferObject) type).getRestrictions();
297 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
299 * @param property Generated property
300 * @return The string used to clone the property, or an empty string
302 static final String cloneCall(final GeneratedProperty property) {
303 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
307 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
308 * and all the methods of the implemented interfaces.
310 * @returns set of method signature instances
312 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
313 methods.addAll(type.getMethodDefinitions());
314 return collectImplementedMethods(type, methods, type.getImplements());
318 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
319 * and recursively their implemented interfaces.
321 * @param methods set of method signatures
322 * @param implementedIfcs list of implemented interfaces
324 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
325 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
326 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
330 ParameterizedType augmentType = null;
331 for (Type implementedIfc : implementedIfcs) {
332 if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
333 final GeneratedType ifc = (GeneratedType) implementedIfc;
334 addImplMethods(methods, ifc);
336 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
337 if (t != null && augmentType == null) {
340 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
341 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
348 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
349 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
350 if (hasOverrideAnnotation(implMethod)) {
351 methods.add(implMethod);
353 final String implMethodName = implMethod.getName();
354 if (BindingMapping.isGetterMethodName(implMethodName)
355 && getterByName(methods, implMethodName).isEmpty()) {
357 methods.add(implMethod);
363 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
364 final String implMethodName) {
365 for (MethodSignature method : methods) {
366 final String methodName = method.getName();
367 if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
368 return Optional.of(method);
371 return Optional.empty();
374 protected static String propertyNameFromGetter(final MethodSignature getter) {
375 return propertyNameFromGetter(getter.getName());
378 protected static String propertyNameFromGetter(final String getterName) {
380 if (BindingMapping.isGetterMethodName(getterName)) {
381 prefix = BindingMapping.GETTER_PREFIX;
382 } else if (BindingMapping.isNonnullMethodName(getterName)) {
383 prefix = BindingMapping.NONNULL_PREFIX;
384 } else if (BindingMapping.isRequireMethodName(getterName)) {
385 prefix = BindingMapping.REQUIRE_PREFIX;
387 throw new IllegalArgumentException(getterName + " is not a getter");
389 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
393 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
395 * @param method Method to examine
396 * @return True if there is an override annotation
398 static boolean hasOverrideAnnotation(final MethodSignature method) {
399 for (final AnnotationType annotation : method.getAnnotations()) {
400 if (OVERRIDE.equals(annotation.getIdentifier())) {
407 static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
408 type.getYangSourceDefinition().ifPresent(def -> {
411 if (def instanceof Single) {
412 final DocumentedNode node = ((Single) def).getNode();
415 .append("This class represents the following YANG schema fragment defined in module <b>")
416 .append(def.getModule().argument().getLocalName()).append("</b>\n")
418 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
421 if (node instanceof SchemaNode) {
422 final SchemaNode schema = (SchemaNode) node;
423 // sb.append("The schema path to identify an instance is\n");
424 // appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
425 // sb.append("</i>\n");
427 if (hasBuilderClass(schema)) {
428 final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
430 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
432 .append("@see ").append(builderName).append('\n');
433 if (node instanceof ListSchemaNode) {
434 final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
435 if (!keyDef.isEmpty()) {
436 sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
442 } else if (def instanceof Multiple) {
443 sb.append("<pre>\n");
444 for (SchemaNode node : ((Multiple) def).getNodes()) {
445 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
447 sb.append("</pre>\n");
452 static String encodeJavadocSymbols(final String description) {
453 // FIXME: Use String.isBlank()?
454 return description == null || description.isEmpty() ? description
455 : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/");
458 private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
459 final DeclaredStatement<?> stmt) {
460 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
461 sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
465 // private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
466 // final List<QName> path) {
467 // if (!path.isEmpty()) {
468 // // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
469 // sb.append(module.argument().getLocalName());
470 // XMLNamespace currentNamespace = path.get(0).getNamespace();
472 // for (QName pathElement : path) {
473 // final XMLNamespace elementNamespace = pathElement.getNamespace();
474 // if (!elementNamespace.equals(currentNamespace)) {
475 // sb.append(pathElement);
476 // currentNamespace = elementNamespace;
478 // sb.append(pathElement.getLocalName());
484 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
485 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
486 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
489 private static boolean isSameProperty(final String getterName1, final String getterName2) {
490 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
494 * Creates set of generated property instances from getter <code>methods</code>.
496 * @param methods set of method signature instances which should be transformed to list of properties
497 * @return set of generated property instances which represents the getter <code>methods</code>
499 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
500 if (methods == null || methods.isEmpty()) {
501 return Collections.emptySet();
503 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
504 for (MethodSignature m : methods) {
505 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
506 if (createdField != null) {
507 result.add(createdField);
514 * Creates generated property instance from the getter <code>method</code> name and return type.
516 * @param method method signature from which is the method name and return type obtained
517 * @return generated property instance for the getter <code>method</code>
518 * @throws IllegalArgumentException <ul>
519 * <li>if the {@code method} equals {@code null}</li>
520 * <li>if the name of the {@code method} equals {@code null}</li>
521 * <li>if the name of the {@code method} is empty</li>
522 * <li>if the return type of the {@code method} equals {@code null}</li>
525 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
526 checkArgument(method != null);
527 checkArgument(method.getReturnType() != null);
528 checkArgument(method.getName() != null);
529 checkArgument(!method.getName().isEmpty());
530 if (method.isDefault()) {
533 if (!BindingMapping.isGetterMethodName(method.getName())) {
537 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
538 return new BuilderGeneratedProperty(fieldName, method);