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