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