Bump upstreams
[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.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME;
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.GETTER_PREFIX;
15
16 import com.google.common.collect.ImmutableSortedSet;
17 import java.lang.reflect.Method;
18 import java.util.AbstractMap;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.LinkedHashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.NoSuchElementException;
28 import java.util.Objects;
29 import java.util.Optional;
30 import java.util.Set;
31 import java.util.regex.Pattern;
32 import java.util.stream.Collectors;
33 import javax.annotation.processing.Generated;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.xtext.xbase.lib.StringExtensions;
36 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
37 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
38 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
41 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
42 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
43 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
44 import org.opendaylight.mdsal.binding.model.api.Restrictions;
45 import org.opendaylight.mdsal.binding.model.api.Type;
46 import org.opendaylight.mdsal.binding.model.ri.Types;
47 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
48 import org.opendaylight.yangtools.yang.binding.Augmentable;
49 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
50
51 /**
52  * Base Java file template. Contains a non-null type and imports which the generated code refers to.
53  */
54 class JavaFileTemplate {
55     /**
56      * {@code java.lang.Class} as a JavaTypeName.
57      */
58     static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
59     /**
60      * {@code java.lang.Deprecated} as a JavaTypeName.
61      */
62     static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
63     /**
64      * {@code java.lang.NullPointerException} as a JavaTypeName.
65      */
66     static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
67     /**
68      * {@code java.lang.NoSuchElementException} as a JavaTypeName.
69      */
70     static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
71     /**
72      * {@code java.lang.Override} as a JavaTypeName.
73      */
74     static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
75     /**
76      * {@code java.lang.void} as a JavaTypeName.
77      */
78     static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
79     /**
80      * {@code java.lang.SuppressWarnings} as a JavaTypeName.
81      */
82     static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
83
84     /**
85      * {@code java.util.Arrays} as a JavaTypeName.
86      */
87     static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
88     /**
89      * {@code java.util.HashMap} as a JavaTypeName.
90      */
91     static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
92     /**
93      * {@code java.util.List} as a JavaTypeName.
94      */
95     static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
96     /**
97      * {@code java.util.Map} as a JavaTypeName.
98      */
99     static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
100     /**
101      * {@code java.util.Objects} as a JavaTypeName.
102      */
103     static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
104     /**
105      * {@code java.util.regex.Pattern} as a JavaTypeName.
106      */
107     static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
108
109     /**
110      * {@code javax.annotation.processing.Generated} as a JavaTypeName.
111      */
112     static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
113
114     /**
115      * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
116      */
117     static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
118     /**
119      * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
120      */
121     static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
122
123     /**
124      * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
125      */
126     static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
127
128     private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
129     private static final Type AUGMENTATION_RET_TYPE;
130
131     static {
132         final Method m;
133         try {
134             m = Augmentable.class.getDeclaredMethod(AUGMENTABLE_AUGMENTATION_NAME, Class.class);
135         } catch (NoSuchMethodException e) {
136             throw new ExceptionInInitializerError(e);
137         }
138
139         AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
140     }
141
142     private final AbstractJavaGeneratedType javaType;
143     private final GeneratedType type;
144
145     JavaFileTemplate(final @NonNull GeneratedType type) {
146         this(new TopLevelJavaGeneratedType(type), type);
147     }
148
149     JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
150         this.javaType = requireNonNull(javaType);
151         this.type = requireNonNull(type);
152     }
153
154     final AbstractJavaGeneratedType javaType() {
155         return javaType;
156     }
157
158     final GeneratedType type() {
159         return type;
160     }
161
162     final String generateImportBlock() {
163         verify(javaType instanceof TopLevelJavaGeneratedType);
164         return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
165                 .collect(Collectors.joining());
166     }
167
168     final @NonNull String importedJavadocName(final @NonNull Type intype) {
169         return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
170     }
171
172     final @NonNull String importedName(final @NonNull Type intype) {
173         return javaType.getReferenceString(intype);
174     }
175
176     final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
177         return javaType.getReferenceString(intype, annotation);
178     }
179
180     final @NonNull String importedName(final Class<?> cls) {
181         return importedName(Types.typeForClass(cls));
182     }
183
184     final @NonNull String importedName(final @NonNull JavaTypeName intype) {
185         return javaType.getReferenceString(intype);
186     }
187
188     final @NonNull String importedNonNull(final @NonNull Type intype) {
189         return importedName(intype, importedName(NONNULL));
190     }
191
192     final @NonNull String importedNullable(final @NonNull Type intype) {
193         return importedName(intype, importedName(NULLABLE));
194     }
195
196     final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
197         return fullyQualifiedName(intype, importedName(NONNULL));
198     }
199
200     final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
201         return javaType.getFullyQualifiedReference(intype, annotation);
202     }
203
204     // Exposed for BuilderTemplate
205     boolean isLocalInnerClass(final JavaTypeName name) {
206         final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
207         return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
208     }
209
210     final CharSequence generateInnerClass(final GeneratedType innerClass) {
211         if (!(innerClass instanceof GeneratedTransferObject)) {
212             return "";
213         }
214
215         final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
216         final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
217         return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
218                 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
219     }
220
221     /**
222      * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
223      * {@link Arrays} if the property is an array, {@link Objects} otherwise.
224      *
225      * @param property Generated property
226      * @return Imported class name
227      */
228     final String importedUtilClass(final GeneratedProperty property) {
229         return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
230     }
231
232     final String generatedAnnotation() {
233         return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
234     }
235
236     /**
237      * Run type analysis, which results in identification of the augmentable type, as well as all methods available
238      * to the type, expressed as properties.
239      */
240     static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
241         final Set<MethodSignature> methods = new LinkedHashSet<>();
242         final Type augmentType = createMethods(type, methods);
243         final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
244                 .build();
245
246         return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
247     }
248
249     static final Restrictions restrictionsForSetter(final Type actualType) {
250         return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
251     }
252
253     static final Restrictions getRestrictions(final Type type) {
254         if (type instanceof ConcreteType) {
255             return ((ConcreteType) type).getRestrictions();
256         }
257         if (type instanceof GeneratedTransferObject) {
258             return ((GeneratedTransferObject) type).getRestrictions();
259         }
260         return null;
261     }
262
263     /**
264      * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
265      *
266      * @param property Generated property
267      * @return The string used to clone the property, or an empty string
268      */
269     static final String cloneCall(final GeneratedProperty property) {
270         return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
271     }
272
273     /**
274      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
275      * and all the methods of the implemented interfaces.
276      *
277      * @returns set of method signature instances
278      */
279     private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
280         methods.addAll(type.getMethodDefinitions());
281         return collectImplementedMethods(type, methods, type.getImplements());
282     }
283
284     /**
285      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
286      * and recursively their implemented interfaces.
287      *
288      * @param methods set of method signatures
289      * @param implementedIfcs list of implemented interfaces
290      */
291     private static ParameterizedType collectImplementedMethods(final GeneratedType type,
292             final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
293         if (implementedIfcs == null || implementedIfcs.isEmpty()) {
294             return null;
295         }
296
297         ParameterizedType augmentType = null;
298         for (Type implementedIfc : implementedIfcs) {
299             if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
300                 final GeneratedType ifc = (GeneratedType) implementedIfc;
301                 addImplMethods(methods, ifc);
302
303                 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
304                 if (t != null && augmentType == null) {
305                     augmentType = t;
306                 }
307             } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
308                 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
309             }
310         }
311
312         return augmentType;
313     }
314
315     private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
316         for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
317             if (hasOverrideAnnotation(implMethod)) {
318                 methods.add(implMethod);
319             } else {
320                 final String implMethodName = implMethod.getName();
321                 if (BindingMapping.isGetterMethodName(implMethodName)
322                         && getterByName(methods, implMethodName).isEmpty()) {
323
324                     methods.add(implMethod);
325                 }
326             }
327         }
328     }
329
330     protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
331             final String implMethodName) {
332         for (MethodSignature method : methods) {
333             final String methodName = method.getName();
334             if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
335                 return Optional.of(method);
336             }
337         }
338         return Optional.empty();
339     }
340
341     protected static String propertyNameFromGetter(final MethodSignature getter) {
342         return propertyNameFromGetter(getter.getName());
343     }
344
345     protected static String propertyNameFromGetter(final String getterName) {
346         final String prefix;
347         if (BindingMapping.isGetterMethodName(getterName)) {
348             prefix = BindingMapping.GETTER_PREFIX;
349         } else if (BindingMapping.isNonnullMethodName(getterName)) {
350             prefix = BindingMapping.NONNULL_PREFIX;
351         } else if (BindingMapping.isRequireMethodName(getterName)) {
352             prefix = BindingMapping.REQUIRE_PREFIX;
353         } else {
354             throw new IllegalArgumentException(getterName + " is not a getter");
355         }
356         return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
357     }
358
359     /**
360      * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
361      *
362      * @param method Method to examine
363      * @return True if there is an override annotation
364      */
365     static boolean hasOverrideAnnotation(final MethodSignature method) {
366         for (final AnnotationType annotation : method.getAnnotations()) {
367             if (OVERRIDE.equals(annotation.getIdentifier())) {
368                 return true;
369             }
370         }
371         return false;
372     }
373
374     private static boolean isSameProperty(final String getterName1, final String getterName2) {
375         return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
376     }
377
378     /**
379      * Creates set of generated property instances from getter <code>methods</code>.
380      *
381      * @param methods set of method signature instances which should be transformed to list of properties
382      * @return set of generated property instances which represents the getter <code>methods</code>
383      */
384     private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
385         if (methods == null || methods.isEmpty()) {
386             return Collections.emptySet();
387         }
388         final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
389         for (MethodSignature m : methods) {
390             final BuilderGeneratedProperty createdField = propertyFromGetter(m);
391             if (createdField != null) {
392                 result.add(createdField);
393             }
394         }
395         return result;
396     }
397
398     /**
399      * Creates generated property instance from the getter <code>method</code> name and return type.
400      *
401      * @param method method signature from which is the method name and return type obtained
402      * @return generated property instance for the getter <code>method</code>
403      * @throws IllegalArgumentException <ul>
404      *                                    <li>if the {@code method} equals {@code null}</li>
405      *                                    <li>if the name of the {@code method} equals {@code null}</li>
406      *                                    <li>if the name of the {@code method} is empty</li>
407      *                                    <li>if the return type of the {@code method} equals {@code null}</li>
408      *                                  </ul>
409      */
410     private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
411         checkArgument(method != null);
412         checkArgument(method.getReturnType() != null);
413         checkArgument(method.getName() != null);
414         checkArgument(!method.getName().isEmpty());
415         if (method.isDefault()) {
416             return null;
417         }
418         if (!BindingMapping.isGetterMethodName(method.getName())) {
419             return null;
420         }
421
422         final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX.length()));
423         return new BuilderGeneratedProperty(fieldName, method);
424     }
425 }