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