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