Do not generate prime when not needed
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / InterfaceTemplate.xtend
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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 extension org.opendaylight.yangtools.yang.binding.contract.Naming.getGetterMethodForNonnull
11 import static extension org.opendaylight.yangtools.yang.binding.contract.Naming.getGetterMethodForRequire
12 import static extension org.opendaylight.yangtools.yang.binding.contract.Naming.isGetterMethodName
13 import static extension org.opendaylight.yangtools.yang.binding.contract.Naming.isNonnullMethodName
14 import static extension org.opendaylight.yangtools.yang.binding.contract.Naming.isRequireMethodName
15 import static org.opendaylight.mdsal.binding.model.ri.Types.BOOLEAN
16 import static org.opendaylight.mdsal.binding.model.ri.Types.STRING
17 import static org.opendaylight.yangtools.yang.binding.contract.Naming.REQUIRE_PREFIX
18 import static org.opendaylight.yangtools.yang.binding.contract.Naming.AUGMENTATION_FIELD
19 import static org.opendaylight.yangtools.yang.binding.contract.Naming.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME
20 import static org.opendaylight.yangtools.yang.binding.contract.Naming.BINDING_EQUALS_NAME
21 import static org.opendaylight.yangtools.yang.binding.contract.Naming.BINDING_HASHCODE_NAME
22 import static org.opendaylight.yangtools.yang.binding.contract.Naming.BINDING_TO_STRING_NAME
23
24 import com.google.common.annotations.VisibleForTesting;
25 import java.util.List
26 import java.util.Locale
27 import java.util.Map.Entry
28 import java.util.Set
29 import org.gaul.modernizer_maven_annotations.SuppressModernizer
30 import org.opendaylight.mdsal.binding.model.api.AnnotationType
31 import org.opendaylight.mdsal.binding.model.api.Constant
32 import org.opendaylight.mdsal.binding.model.api.Enumeration
33 import org.opendaylight.mdsal.binding.model.api.GeneratedType
34 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
35 import org.opendaylight.mdsal.binding.model.api.MethodSignature
36 import org.opendaylight.mdsal.binding.model.api.ParameterizedType
37 import org.opendaylight.mdsal.binding.model.api.Type
38 import org.opendaylight.mdsal.binding.model.ri.Types
39 import org.opendaylight.mdsal.binding.model.ri.TypeConstants
40
41 /**
42  * Template for generating JAVA interfaces.
43  */
44 class InterfaceTemplate extends BaseTemplate {
45     /**
46      * List of constant instances which are generated as JAVA public static final attributes.
47      */
48     val List<Constant> consts
49
50     /**
51      * List of method signatures which are generated as method declarations.
52      */
53     val List<MethodSignature> methods
54
55     /**
56      * List of enumeration which are generated as JAVA enum type.
57      */
58     val List<Enumeration> enums
59
60     /**
61      * List of generated types which are enclosed inside <code>genType</code>
62      */
63     val List<GeneratedType> enclosedGeneratedTypes
64
65     var Entry<Type, Set<BuilderGeneratedProperty>> typeAnalysis
66
67     /**
68      * Creates the instance of this class which is used for generating the interface file source
69      * code from <code>genType</code>.
70      *
71      * @throws NullPointerException if <code>genType</code> is <code>null</code>
72      */
73     new(GeneratedType genType) {
74         super(genType)
75         consts = genType.constantDefinitions
76         methods = genType.methodDefinitions
77         enums = genType.enumerations
78         enclosedGeneratedTypes = genType.enclosedTypes
79     }
80
81     /**
82      * Template method which generate the whole body of the interface.
83      *
84      * @return string with code for interface body in JAVA format
85      */
86     override body() '''
87         «type.formatDataForJavaDoc.wrapToDocumentation»
88         «type.annotations.generateAnnotations»
89         «generatedAnnotation»
90         public interface «type.name»
91             «superInterfaces»
92         {
93
94             «generateInnerClasses»
95
96             «generateEnums»
97
98             «generateConstants»
99
100             «generateMethods»
101
102         }
103
104     '''
105
106     def private generateAnnotations(List<AnnotationType> annotations) '''
107         «IF annotations !== null && !annotations.empty»
108             «FOR annotation : annotations»
109                 «annotation.generateAnnotation»
110             «ENDFOR»
111         «ENDIF»
112     '''
113
114     def private generateAccessorAnnotations(MethodSignature method) '''
115          «val annotations = method.annotations»
116          «IF annotations !== null && !annotations.empty»
117              «FOR annotation : annotations»
118                   «IF !BOOLEAN.equals(method.returnType) || !OVERRIDE.equals(annotation.identifier)»
119                       «annotation.generateAnnotation»
120                   «ENDIF»
121              «ENDFOR»
122         «ENDIF»
123     '''
124
125     /**
126      * Template method which generates the interface name declaration.
127      *
128      * @return string with the code for the interface declaration in JAVA format
129      */
130     def private superInterfaces()
131     '''
132     «IF (!type.implements.empty)»
133          extends
134          «FOR type : type.implements SEPARATOR ","»
135              «type.importedName»
136          «ENDFOR»
137      « ENDIF»
138      '''
139
140     /**
141      * Template method which generates inner classes inside this interface.
142      *
143      * @return string with the source code for inner classes in JAVA format
144      */
145     def private generateInnerClasses() '''
146         «IF !enclosedGeneratedTypes.empty»
147             «FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
148                 «generateInnerClass(innerClass)»
149             «ENDFOR»
150         «ENDIF»
151     '''
152
153     /**
154      * Template method which generates JAVA enum type.
155      *
156      * @return string with inner enum source code in JAVA format
157      */
158     def private generateEnums() '''
159         «IF !enums.empty»
160             «FOR e : enums SEPARATOR "\n"»
161                 «val enumTemplate = new EnumTemplate(javaType.getEnclosedType(e.identifier), e)»
162                 «enumTemplate.generateAsInnerClass»
163             «ENDFOR»
164         «ENDIF»
165     '''
166
167     /**
168      * Template method which generates JAVA constants.
169      *
170      * @return string with constants in JAVA format
171      */
172     def private generateConstants() '''
173         «IF !consts.empty»
174             «FOR c : consts»
175                 «IF !c.name.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
176                     «emitConstant(c)»
177                 «ENDIF»
178             «ENDFOR»
179         «ENDIF»
180     '''
181
182     /**
183      * Template method which generates the declaration of the methods.
184      *
185      * @return string with the declaration of methods source code in JAVA format
186      */
187     def private generateMethods() '''
188         «IF !methods.empty»
189             «FOR m : methods SEPARATOR "\n"»
190                 «IF m.isDefault»
191                     «generateDefaultMethod(m)»
192                 «ELSEIF m.isStatic»
193                     «generateStaticMethod(m)»
194                 «ELSEIF m.parameters.empty && m.name.isGetterMethodName»
195                     «generateAccessorMethod(m)»
196                 «ELSEIF m.parameters.empty && m.name.isNonnullMethodName»
197                     «generateNonnullAccessorMethod(m)»
198                 «ELSE»
199                     «generateMethod(m)»
200                 «ENDIF»
201             «ENDFOR»
202         «ENDIF»
203     '''
204
205     @SuppressModernizer
206     def private generateDefaultMethod(MethodSignature method) {
207         if (method.name.isNonnullMethodName) {
208             generateNonnullMethod(method)
209         } else if (method.name.isRequireMethodName) {
210             generateRequireMethod(method)
211         } else {
212             switch method.name {
213                 case BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME : generateDefaultImplementedInterface
214                 default :
215                     if (VOID.equals(method.returnType.identifier)) {
216                         generateNoopVoidInterfaceMethod(method)
217                     }
218             }
219         }
220     }
221
222     @SuppressModernizer
223     def private generateStaticMethod(MethodSignature method) {
224         switch method.name {
225             case BINDING_EQUALS_NAME : generateBindingEquals
226             case BINDING_HASHCODE_NAME : generateBindingHashCode
227             case BINDING_TO_STRING_NAME : generateBindingToString
228             default : ""
229         }
230     }
231
232     def private generateMethod(MethodSignature method) '''
233         «method.comment.asJavadoc»
234         «method.annotations.generateAnnotations»
235         «method.returnType.importedName» «method.name»(«method.parameters.generateParameters»);
236     '''
237
238     def private generateNoopVoidInterfaceMethod(MethodSignature method) '''
239         «method.comment.asJavadoc»
240         «method.annotations.generateAnnotations»
241         default «VOID.importedName» «method.name»(«method.parameters.generateParameters») {
242             // No-op
243         }
244     '''
245
246     def private accessorJavadoc(MethodSignature method, String orString) {
247         accessorJavadoc(method, orString, null)
248     }
249
250     def private accessorJavadoc(MethodSignature method, String orString, JavaTypeName exception) {
251         val propName = method.propertyNameFromGetter
252         val propReturn = propName + orString
253
254         return wrapToDocumentation('''
255             Return «propReturn»
256
257             «method.comment?.referenceDescription.formatReference»
258             @return {@code «method.returnType.importedName»} «propReturn»
259             «IF exception !== null»
260                 @throws «exception.importedName» if «propName» is not present
261             «ENDIF»
262         ''')
263     }
264
265     def private generateAccessorMethod(MethodSignature method) {
266         return '''
267             «accessorJavadoc(method, ", or {@code null} if it is not present.")»
268             «method.generateAccessorAnnotations»
269             «method.returnType.nullableType» «method.name»();
270         '''
271     }
272
273     def private generateNonnullAccessorMethod(MethodSignature method) {
274         return '''
275             «accessorJavadoc(method, ", or an empty instance if it is not present.")»
276             «method.annotations.generateAnnotations»
277             «method.returnType.importedNonNull» «method.name»();
278         '''
279     }
280
281     def private generateDefaultImplementedInterface() '''
282         @«OVERRIDE.importedName»
283         default «CLASS.importedName»<«type.fullyQualifiedName»> «BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»() {
284             return «type.fullyQualifiedName».class;
285         }
286     '''
287
288     @VisibleForTesting
289     def generateBindingHashCode() '''
290         «val augmentable = analyzeType»
291         «IF augmentable || !typeAnalysis.value.empty»
292             /**
293              * Default implementation of {@link «Object.importedName»#hashCode()} contract for this interface.
294              * Implementations of this interface are encouraged to defer to this method to get consistent hashing
295              * results across all implementations.
296              *
297              * @param obj Object for which to generate hashCode() result.
298              * @return Hash code value of data modeled by this interface.
299              * @throws «NPE.importedName» if {@code obj} is {@code null}
300              */
301             static int «BINDING_HASHCODE_NAME»(final «type.fullyQualifiedNonNull» obj) {
302                 int result = 1;
303                 «val props = typeAnalysis.value»
304                 «IF !props.empty»
305                     final int prime = 31;
306                     «FOR property : props»
307                         result = prime * result + «property.importedUtilClass».hashCode(obj.«property.getterMethodName»());
308                     «ENDFOR»
309                 «ENDIF»
310                 «IF augmentable»
311                     for (var augmentation : obj.augmentations().values()) {
312                         result += augmentation.hashCode();
313                     }
314                 «ENDIF»
315                 return result;
316             }
317         «ENDIF»
318     '''
319
320     def private generateBindingEquals() '''
321         «val augmentable = analyzeType»
322         «IF augmentable || !typeAnalysis.value.isEmpty»
323             /**
324              * Default implementation of {@link «Object.importedName»#equals(«Object.importedName»)} contract for this interface.
325              * Implementations of this interface are encouraged to defer to this method to get consistent equality
326              * results across all implementations.
327              *
328              * @param thisObj Object acting as the receiver of equals invocation
329              * @param obj Object acting as argument to equals invocation
330              * @return True if thisObj and obj are considered equal
331              * @throws «NPE.importedName» if {@code thisObj} is {@code null}
332              */
333             static boolean «BINDING_EQUALS_NAME»(final «type.fullyQualifiedNonNull» thisObj, final «Types.objectType().importedName» obj) {
334                 if (thisObj == obj) {
335                     return true;
336                 }
337                 final var other = «CODEHELPERS.importedName».checkCast(«type.fullyQualifiedName».class, obj);
338                 return other != null
339                     «FOR property : ByTypeMemberComparator.sort(typeAnalysis.value)»
340                         && «property.importedUtilClass».equals(thisObj.«property.getterName»(), other.«property.getterName»())
341                     «ENDFOR»
342                     «IF augmentable»&& thisObj.augmentations().equals(other.augmentations())«ENDIF»;
343             }
344         «ENDIF»
345     '''
346
347     def generateBindingToString() '''
348         «val augmentable = analyzeType»
349         /**
350          * Default implementation of {@link «Object.importedName»#toString()} contract for this interface.
351          * Implementations of this interface are encouraged to defer to this method to get consistent string
352          * representations across all implementations.
353          *
354          * @param obj Object for which to generate toString() result.
355          * @return {@link «STRING.importedName»} value of data modeled by this interface.
356          * @throws «NPE.importedName» if {@code obj} is {@code null}
357          */
358         static «STRING.importedName» «BINDING_TO_STRING_NAME»(final «type.fullyQualifiedNonNull» obj) {
359             final var helper = «MOREOBJECTS.importedName».toStringHelper("«type.name»");
360             «FOR property : typeAnalysis.value»
361                 «CODEHELPERS.importedName».appendValue(helper, "«property.name»", obj.«property.getterName»());
362             «ENDFOR»
363             «IF augmentable»
364                 «CODEHELPERS.importedName».appendAugmentations(helper, "«AUGMENTATION_FIELD»", obj);
365             «ENDIF»
366             return helper.toString();
367         }
368     '''
369
370     def private generateNonnullMethod(MethodSignature method) '''
371         «val ret = method.returnType»
372         «val name = method.name»
373         «accessorJavadoc(method, ", or an empty list if it is not present.")»
374         «method.annotations.generateAnnotations»
375         default «ret.importedNonNull» «name»() {
376             return «CODEHELPERS.importedName».nonnull(«name.getGetterMethodForNonnull»());
377         }
378     '''
379
380     def private generateRequireMethod(MethodSignature method) '''
381         «val ret = method.returnType»
382         «val name = method.name»
383         «val fieldName = name.toLowerCase(Locale.ROOT).replace(REQUIRE_PREFIX, "")»
384         «accessorJavadoc(method, ", guaranteed to be non-null.", NSEE)»
385         default «ret.importedNonNull» «name»() {
386             return «CODEHELPERS.importedName».require(«getGetterMethodForRequire(name)»(), "«fieldName»");
387         }
388     '''
389
390     def private String nullableType(Type type) {
391         if (type.isObject && type instanceof ParameterizedType) {
392             val param = type as ParameterizedType
393             if (Types.isMapType(param) || Types.isListType(param) || Types.isSetType(param)) {
394                 return type.importedNullable
395             }
396         }
397         return type.importedName
398     }
399
400     def private static boolean isObject(Type type) {
401         // The return type has a package, so it's not a primitive type
402         return !type.getPackageName().isEmpty()
403     }
404
405     private def boolean analyzeType() {
406         if (typeAnalysis === null) {
407             typeAnalysis = analyzeTypeHierarchy(type)
408         }
409         typeAnalysis.key !== null
410     }
411 }