Move java,lua api and remaining plugins to src/
[vpp.git] / src / vpp-api / java / jvpp / gen / jvppgen / dto_gen.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2016 Cisco and/or its affiliates.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import os
17 from string import Template
18
19 import util
20
21 dto_template = Template("""
22 package $plugin_package.$dto_package;
23
24 /**
25  * <p>This class represents $description.
26  * <br>It was generated by dto_gen.py based on $inputfile preparsed data:
27  * <pre>
28 $docs
29  * </pre>
30  */
31 public final class $cls_name implements $base_package.$dto_package.$base_type {
32
33 $fields
34 $methods
35 }
36 """)
37
38 field_template = Template("""    public $type $name;\n""")
39
40 send_template = Template("""    @Override
41     public int send(final $base_package.JVpp jvpp) throws io.fd.vpp.jvpp.VppInvocationException {
42         return (($plugin_package.JVpp${plugin_name})jvpp).$method_name($args);
43     }""")
44
45
46 def generate_dtos(func_list, base_package, plugin_package, plugin_name, dto_package, inputfile):
47     """ Generates dto objects in a dedicated package """
48     print "Generating DTOs"
49
50     if not os.path.exists(dto_package):
51         os.mkdir(dto_package)
52
53     for func in func_list:
54         camel_case_dto_name = util.underscore_to_camelcase_upper(func['name'])
55         camel_case_method_name = util.underscore_to_camelcase(func['name'])
56         dto_path = os.path.join(dto_package, camel_case_dto_name + ".java")
57
58         if util.is_ignored(func['name']) or util.is_control_ping(camel_case_dto_name):
59             continue
60
61         fields = generate_dto_fields(camel_case_dto_name, func)
62         methods = generate_dto_base_methods(camel_case_dto_name, func)
63         base_type = ""
64
65         # Generate request/reply or dump/dumpReply even if structure can be used as notification
66         if not util.is_just_notification(func["name"]):
67             if util.is_reply(camel_case_dto_name):
68                 description = "reply DTO"
69                 request_dto_name = get_request_name(camel_case_dto_name, func['name'])
70                 if util.is_details(camel_case_dto_name):
71                     # FIXME assumption that dump calls end with "Dump" suffix. Not enforced in vpe.api
72                     base_type += "JVppReply<%s.%s.%s>" % (plugin_package, dto_package, request_dto_name + "Dump")
73                     generate_dump_reply_dto(request_dto_name, base_package, plugin_package, dto_package,
74                                             camel_case_dto_name, camel_case_method_name, func)
75                 else:
76                     base_type += "JVppReply<%s.%s.%s>" % (plugin_package, dto_package, request_dto_name)
77             else:
78                 args = "" if fields is "" else "this"
79                 methods += send_template.substitute(method_name=camel_case_method_name,
80                                                     base_package=base_package,
81                                                     plugin_package=plugin_package,
82                                                     plugin_name=plugin_name,
83                                                     args=args)
84                 if util.is_dump(camel_case_dto_name):
85                     base_type += "JVppDump"
86                     description = "dump request DTO"
87                 else:
88                     base_type += "JVppRequest"
89                     description = "request DTO"
90
91             write_dto_file(base_package, plugin_package, base_type, camel_case_dto_name, description, dto_package,
92                            dto_path, fields, func, inputfile, methods)
93
94         # for structures that are also used as notifications, generate dedicated notification DTO
95         if util.is_notification(func["name"]):
96             base_type = "JVppNotification"
97             description = "notification DTO"
98             camel_case_dto_name = util.add_notification_suffix(camel_case_dto_name)
99             dto_path = os.path.join(dto_package, camel_case_dto_name + ".java")
100             methods = generate_dto_base_methods(camel_case_dto_name, func)
101             write_dto_file(base_package, plugin_package, base_type, camel_case_dto_name, description, dto_package,
102                            dto_path, fields, func, inputfile, methods)
103
104     flush_dump_reply_dtos(inputfile)
105
106
107 def generate_dto_base_methods(camel_case_dto_name, func):
108     methods = generate_dto_hash(func)
109     methods += generate_dto_equals(camel_case_dto_name, func)
110     methods += generate_dto_tostring(camel_case_dto_name, func)
111     return methods
112
113
114 def generate_dto_fields(camel_case_dto_name, func):
115     fields = ""
116     for t in zip(func['types'], func['args']):
117         # for retval don't generate dto field in Reply
118         field_name = util.underscore_to_camelcase(t[1])
119         if util.is_reply(camel_case_dto_name) and util.is_retval_field(field_name):
120             continue
121         fields += field_template.substitute(type=util.jni_2_java_type_mapping[t[0]],
122                                             name=field_name)
123     return fields
124
125
126 tostring_field_template = Template("""                \"$field_name=\" + $field_name + ", " +\n""")
127 tostring_array_field_template = Template("""                \"$field_name=\" + java.util.Arrays.toString($field_name) + ", " +\n""")
128 tostring_template = Template("""    @Override
129     public String toString() {
130         return "$cls_name{" +
131 $fields_tostring "}";
132     }\n\n""")
133
134
135 def generate_dto_tostring(camel_case_dto_name, func):
136     tostring_fields = ""
137     for t in zip(func['types'], func['args']):
138
139         field_name = util.underscore_to_camelcase(t[1])
140         # for retval don't generate dto field in Reply
141         if util.is_retval_field(field_name):
142             continue
143
144         # handle array types
145         if util.is_array(util.jni_2_java_type_mapping[t[0]]):
146             tostring_fields += tostring_array_field_template.substitute(field_name=field_name)
147         else:
148             tostring_fields += tostring_field_template.substitute(field_name=field_name)
149
150     return tostring_template.substitute(cls_name=camel_case_dto_name,
151                                         fields_tostring=tostring_fields[:-8])
152
153 equals_other_template = Template("""
154         final $cls_name other = ($cls_name) o;
155 \n""")
156 equals_field_template = Template("""        if (!java.util.Objects.equals(this.$field_name, other.$field_name)) {
157             return false;
158         }\n""")
159 equals_array_field_template = Template("""        if (!java.util.Arrays.equals(this.$field_name, other.$field_name)) {
160             return false;
161         }\n""")
162 equals_template = Template("""    @Override
163     public boolean equals(final Object o) {
164         if (this == o) {
165             return true;
166         }
167         if (o == null || getClass() != o.getClass()) {
168             return false;
169         }
170 $comparisons
171         return true;
172     }\n\n""")
173
174
175 def generate_dto_equals(camel_case_dto_name, func):
176     equals_fields = ""
177     for t in zip(func['types'], func['args']):
178         field_name = util.underscore_to_camelcase(t[1])
179         # for retval don't generate dto field in Reply
180         if util.is_retval_field(field_name):
181             continue
182
183         # handle array types
184         if util.is_array(util.jni_2_java_type_mapping[t[0]]):
185             equals_fields += equals_array_field_template.substitute(field_name=field_name)
186         else:
187             equals_fields += equals_field_template.substitute(field_name=field_name)
188
189     if equals_fields != "":
190         equals_fields = equals_other_template.substitute(cls_name=camel_case_dto_name) + equals_fields
191
192     return equals_template.substitute(comparisons=equals_fields)
193
194
195 hash_template = Template("""    @Override
196     public int hashCode() {
197         return java.util.Objects.hash($fields);
198     }\n\n""")
199 hash_single_array_type_template = Template("""    @Override
200     public int hashCode() {
201         return java.util.Arrays.hashCode($fields);
202     }\n\n""")
203
204
205 def generate_dto_hash(func):
206     hash_fields = ""
207
208     # Special handling for hashCode in case just a single array field is present. Cannot use Objects.equals since the
209     # array is mistaken for a varargs parameter. Instead use Arrays.hashCode in such case.
210     if len(func['args']) == 1:
211         single_type = func['types'][0]
212         single_type_name = func['args'][0]
213         if util.is_array(util.jni_2_java_type_mapping[single_type]):
214             return hash_single_array_type_template.substitute(fields=util.underscore_to_camelcase(single_type_name))
215
216     for t in zip(func['types'], func['args']):
217         field_name = util.underscore_to_camelcase(t[1])
218         # for retval don't generate dto field in Reply
219         if util.is_retval_field(field_name):
220             continue
221
222         hash_fields += field_name + ", "
223
224     return hash_template.substitute(fields=hash_fields[:-2])
225
226
227 def write_dto_file(base_package, plugin_package, base_type, camel_case_dto_name, description, dto_package, dto_path,
228                    fields, func, inputfile, methods):
229     dto_file = open(dto_path, 'w')
230     dto_file.write(dto_template.substitute(inputfile=inputfile,
231                                            description=description,
232                                            docs=util.api_message_to_javadoc(func),
233                                            cls_name=camel_case_dto_name,
234                                            fields=fields,
235                                            methods=methods,
236                                            base_package=base_package,
237                                            plugin_package=plugin_package,
238                                            base_type=base_type,
239                                            dto_package=dto_package))
240     dto_file.flush()
241     dto_file.close()
242
243
244 dump_dto_suffix = "ReplyDump"
245 dump_reply_artificial_dtos = {}
246
247
248 # Returns request name or special one from unconventional_naming_rep_req map
249 def get_request_name(camel_case_dto_name, func_name):
250     return util.underscore_to_camelcase_upper(
251         util.unconventional_naming_rep_req[func_name]) if func_name in util.unconventional_naming_rep_req \
252         else util.remove_reply_suffix(camel_case_dto_name)
253
254
255 def flush_dump_reply_dtos(inputfile):
256     for dump_reply_artificial_dto in dump_reply_artificial_dtos.values():
257         dto_path = os.path.join(dump_reply_artificial_dto['dto_package'],
258                                 dump_reply_artificial_dto['cls_name'] + ".java")
259         dto_file = open(dto_path, 'w')
260         dto_file.write(dto_template.substitute(inputfile=inputfile,
261                                                description="dump reply wrapper",
262                                                docs=dump_reply_artificial_dto['docs'],
263                                                cls_name=dump_reply_artificial_dto['cls_name'],
264                                                fields=dump_reply_artificial_dto['fields'],
265                                                methods=dump_reply_artificial_dto['methods'],
266                                                plugin_package=dump_reply_artificial_dto['plugin_package'],
267                                                base_package=dump_reply_artificial_dto['base_package'],
268                                                base_type=dump_reply_artificial_dto['base_type'],
269                                                dto_package=dump_reply_artificial_dto['dto_package']))
270         dto_file.flush()
271         dto_file.close()
272
273
274 def generate_dump_reply_dto(request_dto_name, base_package, plugin_package, dto_package, camel_case_dto_name,
275                             camel_case_method_name, func):
276     base_type = "JVppReplyDump<%s.%s.%s, %s.%s.%s>" % (
277         plugin_package, dto_package, util.remove_reply_suffix(camel_case_dto_name) + "Dump",
278         plugin_package, dto_package, camel_case_dto_name)
279     fields = "    public java.util.List<%s> %s = new java.util.ArrayList<>();" % (camel_case_dto_name, camel_case_method_name)
280     cls_name = camel_case_dto_name + dump_dto_suffix
281     # using artificial type for fields, just to bypass the is_array check in base methods generators
282     # the type is not really used
283     artificial_type = 'u8'
284
285     # In case of already existing artificial reply dump DTO, just update it
286     # Used for sub-dump dtos
287     if request_dto_name in dump_reply_artificial_dtos.keys():
288         dump_reply_artificial_dtos[request_dto_name]['fields'] += '\n' + fields
289         dump_reply_artificial_dtos[request_dto_name]['field_names'].append(func['name'])
290         dump_reply_artificial_dtos[request_dto_name]['field_types'].append(artificial_type)
291         methods = '\n' + generate_dto_base_methods(dump_reply_artificial_dtos[request_dto_name]['cls_name'],
292                                             {'args': dump_reply_artificial_dtos[request_dto_name]['field_names'],
293                                              'types': dump_reply_artificial_dtos[request_dto_name]['field_types']})
294         dump_reply_artificial_dtos[request_dto_name]['methods'] = methods
295     else:
296         methods = '\n' + generate_dto_base_methods(cls_name, {'args': [func['name']],
297                                                               'types': [artificial_type]})
298         dump_reply_artificial_dtos[request_dto_name] = ({'docs': util.api_message_to_javadoc(func),
299                                                          'cls_name': cls_name,
300                                                          'fields': fields,
301                                                          'field_names': [func['name']],
302                                                          'field_types': [artificial_type],
303                                                          # strip too many newlines at the end of base method block
304                                                          'methods': methods,
305                                                          'plugin_package': plugin_package,
306                                                          'base_package': base_package,
307                                                          'base_type': base_type,
308                                                          'dto_package': dto_package})