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