cb0e5c5499a6fbc42b72218f18e822908b55a222
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / JavaFileTemplate.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.java.api.generator;
9
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;
15
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;
27 import java.util.Map;
28 import java.util.NoSuchElementException;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.Set;
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;
66
67 /**
68  * Base Java file template. Contains a non-null type and imports which the generated code refers to.
69  */
70 class JavaFileTemplate {
71     /**
72      * {@code java.lang.Class} as a JavaTypeName.
73      */
74     static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
75     /**
76      * {@code java.lang.Deprecated} as a JavaTypeName.
77      */
78     static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
79     /**
80      * {@code java.lang.NullPointerException} as a JavaTypeName.
81      */
82     static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
83     /**
84      * {@code java.lang.NoSuchElementException} as a JavaTypeName.
85      */
86     static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
87     /**
88      * {@code java.lang.Override} as a JavaTypeName.
89      */
90     static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
91     /**
92      * {@code java.lang.void} as a JavaTypeName.
93      */
94     static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
95     /**
96      * {@code java.lang.SuppressWarnings} as a JavaTypeName.
97      */
98     static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
99
100     /**
101      * {@code java.util.Arrays} as a JavaTypeName.
102      */
103     static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
104     /**
105      * {@code java.util.HashMap} as a JavaTypeName.
106      */
107     static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
108     /**
109      * {@code java.util.List} as a JavaTypeName.
110      */
111     static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
112     /**
113      * {@code java.util.Map} as a JavaTypeName.
114      */
115     static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
116     /**
117      * {@code java.util.Objects} as a JavaTypeName.
118      */
119     static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
120     /**
121      * {@code java.util.regex.Pattern} as a JavaTypeName.
122      */
123     static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
124
125     /**
126      * {@code javax.annotation.processing.Generated} as a JavaTypeName.
127      */
128     static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
129
130     /**
131      * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
132      */
133     static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
134     /**
135      * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
136      */
137     static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
138
139     /**
140      * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
141      */
142     static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
143
144
145     private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
146     private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
147     private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
148     private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
149         .addIgnoredStatement(YangStmtMapping.CONTACT)
150         .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
151         .addIgnoredStatement(YangStmtMapping.REFERENCE)
152         .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
153         .build();
154     private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
155     private static final Type AUGMENTATION_RET_TYPE;
156
157     static {
158         final Method m;
159         try {
160             m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
161         } catch (NoSuchMethodException e) {
162             throw new ExceptionInInitializerError(e);
163         }
164
165         AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
166     }
167
168     private final AbstractJavaGeneratedType javaType;
169     private final GeneratedType type;
170
171     JavaFileTemplate(final @NonNull GeneratedType type) {
172         this(new TopLevelJavaGeneratedType(type), type);
173     }
174
175     JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
176         this.javaType = requireNonNull(javaType);
177         this.type = requireNonNull(type);
178     }
179
180     final AbstractJavaGeneratedType javaType() {
181         return javaType;
182     }
183
184     final GeneratedType type() {
185         return type;
186     }
187
188     final String generateImportBlock() {
189         verify(javaType instanceof TopLevelJavaGeneratedType);
190         return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
191                 .collect(Collectors.joining());
192     }
193
194     final @NonNull String importedJavadocName(final @NonNull Type intype) {
195         return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
196     }
197
198     final @NonNull String importedName(final @NonNull Type intype) {
199         return javaType.getReferenceString(intype);
200     }
201
202     final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
203         return javaType.getReferenceString(intype, annotation);
204     }
205
206     final @NonNull String importedName(final Class<?> cls) {
207         return importedName(Types.typeForClass(cls));
208     }
209
210     final @NonNull String importedName(final @NonNull JavaTypeName intype) {
211         return javaType.getReferenceString(intype);
212     }
213
214     final @NonNull String importedNonNull(final @NonNull Type intype) {
215         return importedName(intype, importedName(NONNULL));
216     }
217
218     final @NonNull String importedNullable(final @NonNull Type intype) {
219         return importedName(intype, importedName(NULLABLE));
220     }
221
222     final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
223         return fullyQualifiedName(intype, importedName(NONNULL));
224     }
225
226     final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
227         return javaType.getFullyQualifiedReference(intype, annotation);
228     }
229
230     // Exposed for BuilderTemplate
231     boolean isLocalInnerClass(final JavaTypeName name) {
232         final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
233         return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
234     }
235
236     final CharSequence generateInnerClass(final GeneratedType innerClass) {
237         if (!(innerClass instanceof GeneratedTransferObject)) {
238             return "";
239         }
240
241         final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
242         final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
243         return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
244                 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
245     }
246
247     /**
248      * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
249      * {@link Arrays} if the property is an array, {@link Objects} otherwise.
250      *
251      * @param property Generated property
252      * @return Imported class name
253      */
254     final String importedUtilClass(final GeneratedProperty property) {
255         return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
256     }
257
258     final String generatedAnnotation() {
259         return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
260     }
261
262     /**
263      * Run type analysis, which results in identification of the augmentable type, as well as all methods available
264      * to the type, expressed as properties.
265      */
266     static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
267         final Set<MethodSignature> methods = new LinkedHashSet<>();
268         final Type augmentType = createMethods(type, methods);
269         final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
270                 .build();
271
272         return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
273     }
274
275     static final Restrictions restrictionsForSetter(final Type actualType) {
276         return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
277     }
278
279     static final Restrictions getRestrictions(final Type type) {
280         if (type instanceof ConcreteType) {
281             return ((ConcreteType) type).getRestrictions();
282         }
283         if (type instanceof GeneratedTransferObject) {
284             return ((GeneratedTransferObject) type).getRestrictions();
285         }
286         return null;
287     }
288
289     /**
290      * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
291      *
292      * @param property Generated property
293      * @return The string used to clone the property, or an empty string
294      */
295     static final String cloneCall(final GeneratedProperty property) {
296         return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
297     }
298
299     /**
300      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
301      * and all the methods of the implemented interfaces.
302      *
303      * @returns set of method signature instances
304      */
305     private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
306         methods.addAll(type.getMethodDefinitions());
307         return collectImplementedMethods(type, methods, type.getImplements());
308     }
309
310     /**
311      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
312      * and recursively their implemented interfaces.
313      *
314      * @param methods set of method signatures
315      * @param implementedIfcs list of implemented interfaces
316      */
317     private static ParameterizedType collectImplementedMethods(final GeneratedType type,
318             final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
319         if (implementedIfcs == null || implementedIfcs.isEmpty()) {
320             return null;
321         }
322
323         ParameterizedType augmentType = null;
324         for (Type implementedIfc : implementedIfcs) {
325             if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
326                 final GeneratedType ifc = (GeneratedType) implementedIfc;
327                 addImplMethods(methods, ifc);
328
329                 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
330                 if (t != null && augmentType == null) {
331                     augmentType = t;
332                 }
333             } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
334                 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
335             }
336         }
337
338         return augmentType;
339     }
340
341     private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
342         for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
343             if (hasOverrideAnnotation(implMethod)) {
344                 methods.add(implMethod);
345             } else {
346                 final String implMethodName = implMethod.getName();
347                 if (BindingMapping.isGetterMethodName(implMethodName)
348                         && getterByName(methods, implMethodName).isEmpty()) {
349
350                     methods.add(implMethod);
351                 }
352             }
353         }
354     }
355
356     protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
357             final String implMethodName) {
358         for (MethodSignature method : methods) {
359             final String methodName = method.getName();
360             if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
361                 return Optional.of(method);
362             }
363         }
364         return Optional.empty();
365     }
366
367     protected static String propertyNameFromGetter(final MethodSignature getter) {
368         return propertyNameFromGetter(getter.getName());
369     }
370
371     protected static String propertyNameFromGetter(final String getterName) {
372         final String prefix;
373         if (BindingMapping.isGetterMethodName(getterName)) {
374             prefix = BindingMapping.GETTER_PREFIX;
375         } else if (BindingMapping.isNonnullMethodName(getterName)) {
376             prefix = BindingMapping.NONNULL_PREFIX;
377         } else if (BindingMapping.isRequireMethodName(getterName)) {
378             prefix = BindingMapping.REQUIRE_PREFIX;
379         } else {
380             throw new IllegalArgumentException(getterName + " is not a getter");
381         }
382         return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
383     }
384
385     /**
386      * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
387      *
388      * @param method Method to examine
389      * @return True if there is an override annotation
390      */
391     static boolean hasOverrideAnnotation(final MethodSignature method) {
392         for (final AnnotationType annotation : method.getAnnotations()) {
393             if (OVERRIDE.equals(annotation.getIdentifier())) {
394                 return true;
395             }
396         }
397         return false;
398     }
399
400     static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
401         type.getYangSourceDefinition().ifPresent(def -> {
402             sb.append('\n');
403
404             if (def instanceof Single) {
405                 final DocumentedNode node = ((Single) def).getNode();
406
407                 sb.append("<p>\n")
408                     .append("This class represents the following YANG schema fragment defined in module <b>")
409                     .append(def.getModule().argument().getLocalName()).append("</b>\n")
410                     .append("<pre>\n");
411                 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
412                 sb.append("</pre>");
413
414                 if (node instanceof SchemaNode) {
415                     final SchemaNode schema = (SchemaNode) node;
416                     sb.append("The schema path to identify an instance is\n");
417                     appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
418                     sb.append("</i>\n");
419
420                     if (hasBuilderClass(schema)) {
421                         final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
422
423                         sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
424                         .append("}.\n")
425                         .append("@see ").append(builderName).append('\n');
426                         if (node instanceof ListSchemaNode) {
427                             final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
428                             if (!keyDef.isEmpty()) {
429                                 sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
430                             }
431                             sb.append('\n');
432                         }
433                     }
434                 }
435             } else if (def instanceof Multiple) {
436                 sb.append("<pre>\n");
437                 for (SchemaNode node : ((Multiple) def).getNodes()) {
438                     appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
439                 }
440                 sb.append("</pre>\n");
441             }
442         });
443     }
444
445     static String encodeJavadocSymbols(final String description) {
446         // FIXME: Use String.isBlank()?
447         return description == null || description.isEmpty() ? description
448             : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&amp;")).replaceAll("&#42;&#47;");
449     }
450
451     private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
452         final DeclaredStatement<?> stmt) {
453         for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
454             sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
455         }
456     }
457
458     private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
459             final List<QName> path) {
460         if (!path.isEmpty()) {
461             // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
462             sb.append(module.argument().getLocalName());
463             XMLNamespace currentNamespace = path.get(0).getNamespace();
464
465             for (QName pathElement : path) {
466                 final XMLNamespace elementNamespace = pathElement.getNamespace();
467                 if (!elementNamespace.equals(currentNamespace)) {
468                     sb.append(pathElement);
469                     currentNamespace = elementNamespace;
470                 } else {
471                     sb.append(pathElement.getLocalName());
472                 }
473             }
474         }
475     }
476
477     private static boolean hasBuilderClass(final SchemaNode schemaNode) {
478         return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
479                 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
480     }
481
482     private static boolean isSameProperty(final String getterName1, final String getterName2) {
483         return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
484     }
485
486     /**
487      * Creates set of generated property instances from getter <code>methods</code>.
488      *
489      * @param methods set of method signature instances which should be transformed to list of properties
490      * @return set of generated property instances which represents the getter <code>methods</code>
491      */
492     private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
493         if (methods == null || methods.isEmpty()) {
494             return Collections.emptySet();
495         }
496         final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
497         for (MethodSignature m : methods) {
498             final BuilderGeneratedProperty createdField = propertyFromGetter(m);
499             if (createdField != null) {
500                 result.add(createdField);
501             }
502         }
503         return result;
504     }
505
506     /**
507      * Creates generated property instance from the getter <code>method</code> name and return type.
508      *
509      * @param method method signature from which is the method name and return type obtained
510      * @return generated property instance for the getter <code>method</code>
511      * @throws IllegalArgumentException <ul>
512      *                                    <li>if the {@code method} equals {@code null}</li>
513      *                                    <li>if the name of the {@code method} equals {@code null}</li>
514      *                                    <li>if the name of the {@code method} is empty</li>
515      *                                    <li>if the return type of the {@code method} equals {@code null}</li>
516      *                                  </ul>
517      */
518     private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
519         checkArgument(method != null);
520         checkArgument(method.getReturnType() != null);
521         checkArgument(method.getName() != null);
522         checkArgument(!method.getName().isEmpty());
523         if (method.isDefault()) {
524             return null;
525         }
526         if (!BindingMapping.isGetterMethodName(method.getName())) {
527             return null;
528         }
529
530         final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
531         return new BuilderGeneratedProperty(fieldName, method);
532     }
533 }