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