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