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.collect.ImmutableSortedSet;
18 import java.lang.reflect.Method;
19 import java.util.AbstractMap;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.LinkedHashSet;
26 import java.util.List;
28 import java.util.NoSuchElementException;
29 import java.util.Objects;
30 import java.util.Optional;
32 import java.util.regex.Pattern;
33 import java.util.stream.Collectors;
34 import javax.annotation.processing.Generated;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.eclipse.xtext.xbase.lib.StringExtensions;
37 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
38 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
42 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
43 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
44 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
45 import org.opendaylight.mdsal.binding.model.api.Restrictions;
46 import org.opendaylight.mdsal.binding.model.api.Type;
47 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple;
48 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single;
49 import org.opendaylight.mdsal.binding.model.ri.Types;
50 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
51 import org.opendaylight.yangtools.yang.binding.Augmentable;
52 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.XMLNamespace;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
62 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
63 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
64 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
65 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter;
68 * Base Java file template. Contains a non-null type and imports which the generated code refers to.
70 class JavaFileTemplate {
72 * {@code java.lang.Class} as a JavaTypeName.
74 static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
76 * {@code java.lang.Deprecated} as a JavaTypeName.
78 static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
80 * {@code java.lang.NullPointerException} as a JavaTypeName.
82 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
84 * {@code java.lang.NoSuchElementException} as a JavaTypeName.
86 static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
88 * {@code java.lang.Override} as a JavaTypeName.
90 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
92 * {@code java.lang.void} as a JavaTypeName.
94 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
96 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
98 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
101 * {@code java.util.Arrays} as a JavaTypeName.
103 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
105 * {@code java.util.HashMap} as a JavaTypeName.
107 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
109 * {@code java.util.List} as a JavaTypeName.
111 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
113 * {@code java.util.Map} as a JavaTypeName.
115 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
117 * {@code java.util.Objects} as a JavaTypeName.
119 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
121 * {@code java.util.regex.Pattern} as a JavaTypeName.
123 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
126 * {@code javax.annotation.processing.Generated} as a JavaTypeName.
128 static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
131 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
133 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
135 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
137 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
140 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
142 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
144 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
145 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
146 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
147 private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
148 .addIgnoredStatement(YangStmtMapping.CONTACT)
149 .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
150 .addIgnoredStatement(YangStmtMapping.REFERENCE)
151 .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
153 private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
154 private static final Type AUGMENTATION_RET_TYPE;
159 m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
160 } catch (NoSuchMethodException e) {
161 throw new ExceptionInInitializerError(e);
164 AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
167 private final AbstractJavaGeneratedType javaType;
168 private final GeneratedType type;
170 JavaFileTemplate(final @NonNull GeneratedType type) {
171 this(new TopLevelJavaGeneratedType(type), type);
174 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
175 this.javaType = requireNonNull(javaType);
176 this.type = requireNonNull(type);
179 final AbstractJavaGeneratedType javaType() {
183 final GeneratedType type() {
187 final String generateImportBlock() {
188 verify(javaType instanceof TopLevelJavaGeneratedType);
189 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
190 .collect(Collectors.joining());
193 final @NonNull String importedJavadocName(final @NonNull Type intype) {
194 return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
197 final @NonNull String importedName(final @NonNull Type intype) {
198 return javaType.getReferenceString(intype);
201 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
202 return javaType.getReferenceString(intype, annotation);
205 final @NonNull String importedName(final Class<?> cls) {
206 return importedName(Types.typeForClass(cls));
209 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
210 return javaType.getReferenceString(intype);
213 final @NonNull String importedNonNull(final @NonNull Type intype) {
214 return importedName(intype, importedName(NONNULL));
217 final @NonNull String importedNullable(final @NonNull Type intype) {
218 return importedName(intype, importedName(NULLABLE));
221 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
222 return fullyQualifiedName(intype, importedName(NONNULL));
225 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
226 return javaType.getFullyQualifiedReference(intype, annotation);
229 // Exposed for BuilderTemplate
230 boolean isLocalInnerClass(final JavaTypeName name) {
231 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
232 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
235 final CharSequence generateInnerClass(final GeneratedType innerClass) {
236 if (!(innerClass instanceof GeneratedTransferObject)) {
240 final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
241 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
242 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
243 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
247 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
248 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
250 * @param property Generated property
251 * @return Imported class name
253 final String importedUtilClass(final GeneratedProperty property) {
254 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
257 final String generatedAnnotation() {
258 return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
262 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
263 * to the type, expressed as properties.
265 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
266 final Set<MethodSignature> methods = new LinkedHashSet<>();
267 final Type augmentType = createMethods(type, methods);
268 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
271 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
274 static final Restrictions restrictionsForSetter(final Type actualType) {
275 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
278 static final Restrictions getRestrictions(final Type type) {
279 if (type instanceof ConcreteType) {
280 return ((ConcreteType) type).getRestrictions();
282 if (type instanceof GeneratedTransferObject) {
283 return ((GeneratedTransferObject) type).getRestrictions();
289 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
291 * @param property Generated property
292 * @return The string used to clone the property, or an empty string
294 static final String cloneCall(final GeneratedProperty property) {
295 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
299 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
300 * and all the methods of the implemented interfaces.
302 * @returns set of method signature instances
304 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
305 methods.addAll(type.getMethodDefinitions());
306 return collectImplementedMethods(type, methods, type.getImplements());
310 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
311 * and recursively their implemented interfaces.
313 * @param methods set of method signatures
314 * @param implementedIfcs list of implemented interfaces
316 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
317 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
318 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
322 ParameterizedType augmentType = null;
323 for (Type implementedIfc : implementedIfcs) {
324 if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
325 final GeneratedType ifc = (GeneratedType) implementedIfc;
326 addImplMethods(methods, ifc);
328 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
329 if (t != null && augmentType == null) {
332 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
333 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
340 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
341 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
342 if (hasOverrideAnnotation(implMethod)) {
343 methods.add(implMethod);
345 final String implMethodName = implMethod.getName();
346 if (BindingMapping.isGetterMethodName(implMethodName)
347 && getterByName(methods, implMethodName).isEmpty()) {
349 methods.add(implMethod);
355 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
356 final String implMethodName) {
357 for (MethodSignature method : methods) {
358 final String methodName = method.getName();
359 if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
360 return Optional.of(method);
363 return Optional.empty();
366 protected static String propertyNameFromGetter(final MethodSignature getter) {
367 return propertyNameFromGetter(getter.getName());
370 protected static String propertyNameFromGetter(final String getterName) {
372 if (BindingMapping.isGetterMethodName(getterName)) {
373 prefix = BindingMapping.GETTER_PREFIX;
374 } else if (BindingMapping.isNonnullMethodName(getterName)) {
375 prefix = BindingMapping.NONNULL_PREFIX;
376 } else if (BindingMapping.isRequireMethodName(getterName)) {
377 prefix = BindingMapping.REQUIRE_PREFIX;
379 throw new IllegalArgumentException(getterName + " is not a getter");
381 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
385 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
387 * @param method Method to examine
388 * @return True if there is an override annotation
390 static boolean hasOverrideAnnotation(final MethodSignature method) {
391 for (final AnnotationType annotation : method.getAnnotations()) {
392 if (OVERRIDE.equals(annotation.getIdentifier())) {
399 static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
400 type.getYangSourceDefinition().ifPresent(def -> {
403 if (def instanceof Single) {
404 final DocumentedNode node = ((Single) def).getNode();
407 .append("This class represents the following YANG schema fragment defined in module <b>")
408 .append(def.getModule().argument().getLocalName()).append("</b>\n")
410 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
413 if (node instanceof SchemaNode) {
414 final SchemaNode schema = (SchemaNode) node;
415 sb.append("The schema path to identify an instance is\n");
416 appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
419 if (hasBuilderClass(schema)) {
420 final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
422 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
424 .append("@see ").append(builderName).append('\n');
425 if (node instanceof ListSchemaNode) {
426 final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
427 if (!keyDef.isEmpty()) {
428 sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
434 } else if (def instanceof Multiple) {
435 sb.append("<pre>\n");
436 for (SchemaNode node : ((Multiple) def).getNodes()) {
437 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
439 sb.append("</pre>\n");
444 static String encodeJavadocSymbols(final String description) {
445 // FIXME: Use String.isBlank()?
446 return description == null || description.isEmpty() ? description
447 : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/");
450 private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
451 final DeclaredStatement<?> stmt) {
452 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
453 sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
457 private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
458 final List<QName> path) {
459 if (!path.isEmpty()) {
460 // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
461 sb.append(module.argument().getLocalName());
462 XMLNamespace currentNamespace = path.get(0).getNamespace();
464 for (QName pathElement : path) {
465 final XMLNamespace elementNamespace = pathElement.getNamespace();
466 if (!elementNamespace.equals(currentNamespace)) {
467 sb.append(pathElement);
468 currentNamespace = elementNamespace;
470 sb.append(pathElement.getLocalName());
476 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
477 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
478 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
481 private static boolean isSameProperty(final String getterName1, final String getterName2) {
482 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
486 * Creates set of generated property instances from getter <code>methods</code>.
488 * @param methods set of method signature instances which should be transformed to list of properties
489 * @return set of generated property instances which represents the getter <code>methods</code>
491 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
492 if (methods == null || methods.isEmpty()) {
493 return Collections.emptySet();
495 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
496 for (MethodSignature m : methods) {
497 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
498 if (createdField != null) {
499 result.add(createdField);
506 * Creates generated property instance from the getter <code>method</code> name and return type.
508 * @param method method signature from which is the method name and return type obtained
509 * @return generated property instance for the getter <code>method</code>
510 * @throws IllegalArgumentException <ul>
511 * <li>if the {@code method} equals {@code null}</li>
512 * <li>if the name of the {@code method} equals {@code null}</li>
513 * <li>if the name of the {@code method} is empty</li>
514 * <li>if the return type of the {@code method} equals {@code null}</li>
517 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
518 checkArgument(method != null);
519 checkArgument(method.getReturnType() != null);
520 checkArgument(method.getName() != null);
521 checkArgument(!method.getName().isEmpty());
522 if (method.isDefault()) {
525 if (!BindingMapping.isGetterMethodName(method.getName())) {
529 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
530 return new BuilderGeneratedProperty(fieldName, method);