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.NullPointerException} as a JavaTypeName.
81 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
83 * {@code java.lang.NoSuchElementException} as a JavaTypeName.
85 static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
87 * {@code java.lang.Override} as a JavaTypeName.
89 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
91 * {@code java.lang.void} as a JavaTypeName.
93 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
95 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
97 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
100 * {@code java.util.Arrays} as a JavaTypeName.
102 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
104 * {@code java.util.HashMap} as a JavaTypeName.
106 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
108 * {@code java.util.List} as a JavaTypeName.
110 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
112 * {@code java.util.Map} as a JavaTypeName.
114 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
116 * {@code java.util.Objects} as a JavaTypeName.
118 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
120 * {@code java.util.regex.Pattern} as a JavaTypeName.
122 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
125 * {@code javax.annotation.processing.Generated} as a JavaTypeName.
127 static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
130 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
132 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
134 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
136 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
139 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
141 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
144 * {@code com.google.common.base.MoreObjects} as a JavaTypeName.
146 static final @NonNull JavaTypeName MOREOBJECTS = JavaTypeName.create(MoreObjects.class);
148 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
149 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
150 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
151 private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
152 .addIgnoredStatement(YangStmtMapping.CONTACT)
153 .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
154 .addIgnoredStatement(YangStmtMapping.REFERENCE)
155 .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
157 private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
158 private static final Type AUGMENTATION_RET_TYPE;
163 m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
164 } catch (NoSuchMethodException e) {
165 throw new ExceptionInInitializerError(e);
168 AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
171 private final AbstractJavaGeneratedType javaType;
172 private final GeneratedType type;
174 JavaFileTemplate(final @NonNull GeneratedType type) {
175 this(new TopLevelJavaGeneratedType(type), type);
178 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
179 this.javaType = requireNonNull(javaType);
180 this.type = requireNonNull(type);
183 final AbstractJavaGeneratedType javaType() {
187 final GeneratedType type() {
191 final String generateImportBlock() {
192 verify(javaType instanceof TopLevelJavaGeneratedType);
193 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
194 .collect(Collectors.joining());
197 final @NonNull String importedJavadocName(final @NonNull Type intype) {
198 return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
201 final @NonNull String importedName(final @NonNull Type intype) {
202 return javaType.getReferenceString(intype);
205 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
206 return javaType.getReferenceString(intype, annotation);
209 final @NonNull String importedName(final Class<?> cls) {
210 return importedName(Types.typeForClass(cls));
213 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
214 return javaType.getReferenceString(intype);
217 final @NonNull String importedNonNull(final @NonNull Type intype) {
218 return importedName(intype, importedName(NONNULL));
221 final @NonNull String importedNullable(final @NonNull Type intype) {
222 return importedName(intype, importedName(NULLABLE));
225 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
226 return fullyQualifiedName(intype, importedName(NONNULL));
229 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
230 return javaType.getFullyQualifiedReference(intype, annotation);
233 // Exposed for BuilderTemplate
234 boolean isLocalInnerClass(final JavaTypeName name) {
235 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
236 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
239 final CharSequence generateInnerClass(final GeneratedType innerClass) {
240 if (!(innerClass instanceof GeneratedTransferObject)) {
244 final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
245 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
246 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
247 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
251 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
252 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
254 * @param property Generated property
255 * @return Imported class name
257 final String importedUtilClass(final GeneratedProperty property) {
258 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
261 final String generatedAnnotation() {
262 return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
266 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
267 * to the type, expressed as properties.
269 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
270 final Set<MethodSignature> methods = new LinkedHashSet<>();
271 final Type augmentType = createMethods(type, methods);
272 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
275 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
278 static final Restrictions restrictionsForSetter(final Type actualType) {
279 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
282 static final Restrictions getRestrictions(final Type type) {
283 if (type instanceof ConcreteType) {
284 return ((ConcreteType) type).getRestrictions();
286 if (type instanceof GeneratedTransferObject) {
287 return ((GeneratedTransferObject) type).getRestrictions();
293 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
295 * @param property Generated property
296 * @return The string used to clone the property, or an empty string
298 static final String cloneCall(final GeneratedProperty property) {
299 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
303 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
304 * and all the methods of the implemented interfaces.
306 * @returns set of method signature instances
308 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
309 methods.addAll(type.getMethodDefinitions());
310 return collectImplementedMethods(type, methods, type.getImplements());
314 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
315 * and recursively their implemented interfaces.
317 * @param methods set of method signatures
318 * @param implementedIfcs list of implemented interfaces
320 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
321 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
322 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
326 ParameterizedType augmentType = null;
327 for (Type implementedIfc : implementedIfcs) {
328 if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
329 final GeneratedType ifc = (GeneratedType) implementedIfc;
330 addImplMethods(methods, ifc);
332 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
333 if (t != null && augmentType == null) {
336 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
337 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
344 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
345 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
346 if (hasOverrideAnnotation(implMethod)) {
347 methods.add(implMethod);
349 final String implMethodName = implMethod.getName();
350 if (BindingMapping.isGetterMethodName(implMethodName)
351 && getterByName(methods, implMethodName).isEmpty()) {
353 methods.add(implMethod);
359 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
360 final String implMethodName) {
361 for (MethodSignature method : methods) {
362 final String methodName = method.getName();
363 if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
364 return Optional.of(method);
367 return Optional.empty();
370 protected static String propertyNameFromGetter(final MethodSignature getter) {
371 return propertyNameFromGetter(getter.getName());
374 protected static String propertyNameFromGetter(final String getterName) {
376 if (BindingMapping.isGetterMethodName(getterName)) {
377 prefix = BindingMapping.GETTER_PREFIX;
378 } else if (BindingMapping.isNonnullMethodName(getterName)) {
379 prefix = BindingMapping.NONNULL_PREFIX;
380 } else if (BindingMapping.isRequireMethodName(getterName)) {
381 prefix = BindingMapping.REQUIRE_PREFIX;
383 throw new IllegalArgumentException(getterName + " is not a getter");
385 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
389 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
391 * @param method Method to examine
392 * @return True if there is an override annotation
394 static boolean hasOverrideAnnotation(final MethodSignature method) {
395 for (final AnnotationType annotation : method.getAnnotations()) {
396 if (OVERRIDE.equals(annotation.getIdentifier())) {
403 static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
404 type.getYangSourceDefinition().ifPresent(def -> {
407 if (def instanceof Single) {
408 final DocumentedNode node = ((Single) def).getNode();
411 .append("This class represents the following YANG schema fragment defined in module <b>")
412 .append(def.getModule().argument().getLocalName()).append("</b>\n")
414 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
417 if (node instanceof SchemaNode) {
418 final SchemaNode schema = (SchemaNode) node;
419 // sb.append("The schema path to identify an instance is\n");
420 // appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
421 // sb.append("</i>\n");
423 if (hasBuilderClass(schema)) {
424 final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
426 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
428 .append("@see ").append(builderName).append('\n');
429 if (node instanceof ListSchemaNode) {
430 final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
431 if (!keyDef.isEmpty()) {
432 sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
438 } else if (def instanceof Multiple) {
439 sb.append("<pre>\n");
440 for (SchemaNode node : ((Multiple) def).getNodes()) {
441 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
443 sb.append("</pre>\n");
448 static String encodeJavadocSymbols(final String description) {
449 // FIXME: Use String.isBlank()?
450 return description == null || description.isEmpty() ? description
451 : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/");
454 private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
455 final DeclaredStatement<?> stmt) {
456 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
457 sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
461 // private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
462 // final List<QName> path) {
463 // if (!path.isEmpty()) {
464 // // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
465 // sb.append(module.argument().getLocalName());
466 // XMLNamespace currentNamespace = path.get(0).getNamespace();
468 // for (QName pathElement : path) {
469 // final XMLNamespace elementNamespace = pathElement.getNamespace();
470 // if (!elementNamespace.equals(currentNamespace)) {
471 // sb.append(pathElement);
472 // currentNamespace = elementNamespace;
474 // sb.append(pathElement.getLocalName());
480 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
481 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
482 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
485 private static boolean isSameProperty(final String getterName1, final String getterName2) {
486 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
490 * Creates set of generated property instances from getter <code>methods</code>.
492 * @param methods set of method signature instances which should be transformed to list of properties
493 * @return set of generated property instances which represents the getter <code>methods</code>
495 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
496 if (methods == null || methods.isEmpty()) {
497 return Collections.emptySet();
499 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
500 for (MethodSignature m : methods) {
501 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
502 if (createdField != null) {
503 result.add(createdField);
510 * Creates generated property instance from the getter <code>method</code> name and return type.
512 * @param method method signature from which is the method name and return type obtained
513 * @return generated property instance for the getter <code>method</code>
514 * @throws IllegalArgumentException <ul>
515 * <li>if the {@code method} equals {@code null}</li>
516 * <li>if the name of the {@code method} equals {@code null}</li>
517 * <li>if the name of the {@code method} is empty</li>
518 * <li>if the return type of the {@code method} equals {@code null}</li>
521 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
522 checkArgument(method != null);
523 checkArgument(method.getReturnType() != null);
524 checkArgument(method.getName() != null);
525 checkArgument(!method.getName().isEmpty());
526 if (method.isDefault()) {
529 if (!BindingMapping.isGetterMethodName(method.getName())) {
533 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
534 return new BuilderGeneratedProperty(fieldName, method);