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