2 # Copyright (c) 2020 Cisco and/or its affiliates.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 # Provide two classes FromJSON and TOJSON that converts between JSON and VPP's
22 This module creates C code for core VPP, VPP plugins and client side VAT and
30 from io import StringIO
33 process_imports = False
36 ###############################################################################
38 '''Class to generate functions converting from VPP binary API to JSON.'''
40 noprint_fields = {'_vl_msg_id': None,
43 is_number = {'u8': None,
54 def __init__(self, module, types, defines, imported_types, stream):
57 self.defines = defines
59 self.types_hash = {'vl_api_'+d.name+'_t':
60 d for d in types + imported_types}
61 self.defines_hash = {d.name: d for d in defines}
64 '''Output the top boilerplate.'''
65 write = self.stream.write
66 write('#ifndef included_{}_api_tojson_h\n'.format(self.module))
67 write('#define included_{}_api_tojson_h\n'.format(self.module))
68 write('#include <vppinfra/cJSON.h>\n\n')
69 write('#include <vat2/jsonconvert.h>\n\n')
72 '''Output the bottom boilerplate.'''
73 write = self.stream.write
76 def get_json_func(self, t):
77 '''Given the type, returns the function to use to create a
81 vt = self.types_hash[t]
82 if vt.type == 'Using' and 'length' not in vt.alias:
83 vt_type = vt.alias['type']
87 if t in self.is_number or vt_type in self.is_number:
88 return 'cJSON_AddNumberToObject', '', False
90 return 'cJSON_AddBoolToObject', '', False
92 # Lookup type name check if it's enum
93 if vt.type == 'Enum' or vt.type == 'EnumFlag':
94 return '{t}_tojson'.format(t=t), '', True
95 return '{t}_tojson'.format(t=t), '&', True
97 def get_json_array_func(self, t):
98 '''Given a type returns the function to create a cJSON object
100 if t in self.is_number:
101 return 'cJSON_CreateNumber', ''
103 return 'cJSON_CreateBool', ''
104 return '{t}_tojson'.format(t=t), '&'
106 def print_string(self, o):
107 '''Create cJSON object from vl_api_string_t'''
108 write = self.stream.write
110 write(' vl_api_string_cJSON_AddToObject(o, "{n}", &a->{n});\n'
111 .format(n=o.fieldname))
114 write(' cJSON_AddStringToObject(o, "{n}", (char *)a->{n});\n'
115 .format(n=o.fieldname))
117 def print_field(self, o):
118 '''Called for every field in a typedef or define.'''
119 write = self.stream.write
120 if o.fieldname in self.noprint_fields:
123 f, p, newobj = self.get_json_func(o.fieldtype)
126 write(' cJSON_AddItemToObject(o, "{n}", {f}({p}a->{n}));\n'
127 .format(f=f, p=p, n=o.fieldname))
129 write(' {f}(o, "{n}", {p}a->{n});\n'
130 .format(f=f, p=p, n=o.fieldname))
132 _dispatch['Field'] = print_field
134 def print_array(self, o):
135 '''Converts a VPP API array to cJSON array.'''
136 write = self.stream.write
141 cJSON *array = cJSON_AddArrayToObject(o, "{n}");
142 for (i = 0; i < {lfield}; i++) {{
143 cJSON_AddItemToArray(array, {f}({p}a->{n}[i]));
148 if o.fieldtype == 'string':
152 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
153 if o.fieldtype == 'u8':
155 # What is length field doing here?
156 write(' u8 *s = format(0, "0x%U", format_hex_bytes, '
157 '&a->{n}, {lfield});\n'
158 .format(n=o.fieldname, lfield=lfield))
159 write(' cJSON_AddStringToObject(o, "{n}", (char *)s);\n'
160 .format(n=o.fieldname))
161 write(' vec_free(s);\n')
165 f, p = self.get_json_array_func(o.fieldtype)
166 write(forloop.format(lfield=lfield,
172 _dispatch['Array'] = print_array
174 def print_enum(self, o):
175 '''Create cJSON object (string) for VPP API enum'''
176 write = self.stream.write
177 write('static inline cJSON *vl_api_{name}_t_tojson '
178 '(vl_api_{name}_t a) {{\n'.format(name=o.name))
180 write(" switch(a) {\n")
182 write(" case %s:\n" % b[1])
183 write(' return cJSON_CreateString("{}");\n'.format(b[0]))
184 write(' default: return cJSON_CreateString("Invalid ENUM");\n')
186 write(' return 0;\n')
189 _dispatch['Enum'] = print_enum
191 def print_enum_flag(self, o):
192 '''Create cJSON object (string) for VPP API enum'''
193 write = self.stream.write
194 write('static inline cJSON *vl_api_{name}_t_tojson '
195 '(vl_api_{name}_t a) {{\n'.format(name=o.name))
196 write(' cJSON *array = cJSON_CreateArray();\n')
199 write(' if (a & {})\n'.format(b[0]))
200 write(' cJSON_AddItemToArray(array, cJSON_CreateString("{}"));\n'.format(b[0]))
201 write(' return array;\n')
204 _dispatch['EnumFlag'] = print_enum_flag
206 def print_typedef(self, o):
207 '''Create cJSON (dictionary) object from VPP API typedef'''
208 write = self.stream.write
209 write('static inline cJSON *vl_api_{name}_t_tojson '
210 '(vl_api_{name}_t *a) {{\n'.format(name=o.name))
211 write(' cJSON *o = cJSON_CreateObject();\n')
214 self._dispatch[t.type](self, t)
216 write(' return o;\n')
219 def print_define(self, o):
220 '''Create cJSON (dictionary) object from VPP API define'''
221 write = self.stream.write
222 write('static inline cJSON *vl_api_{name}_t_tojson '
223 '(vl_api_{name}_t *a) {{\n'.format(name=o.name))
224 write(' cJSON *o = cJSON_CreateObject();\n')
225 write(' cJSON_AddStringToObject(o, "_msgname", "{}");\n'
229 self._dispatch[t.type](self, t)
231 write(' return o;\n')
234 def print_using(self, o):
235 '''Create cJSON (dictionary) object from VPP API aliased type'''
239 write = self.stream.write
240 write('static inline cJSON *vl_api_{name}_t_tojson '
241 '(vl_api_{name}_t *a) {{\n'.format(name=o.name))
243 write(' u8 *s = format(0, "%U", format_vl_api_{}_t, a);\n'
245 write(' cJSON *o = cJSON_CreateString((char *)s);\n')
246 write(' vec_free(s);\n')
247 write(' return o;\n')
250 _dispatch['Typedef'] = print_typedef
251 _dispatch['Define'] = print_define
252 _dispatch['Using'] = print_using
253 _dispatch['Union'] = print_typedef
255 def generate_function(self, t):
256 '''Main entry point'''
257 write = self.stream.write
259 write('/* Manual print {} */\n'.format(t.name))
261 self._dispatch[t.type](self, t)
263 def generate_types(self):
264 '''Main entry point'''
266 self.generate_function(t)
268 def generate_defines(self):
269 '''Main entry point'''
270 for t in self.defines:
271 self.generate_function(t)
276 Parse JSON objects into VPP API binary message structures.
279 noprint_fields = {'_vl_msg_id': None,
280 'client_index': None,
282 is_number = {'u8': None,
293 def __init__(self, module, types, defines, imported_types, stream):
296 self.defines = defines
298 self.types_hash = {'vl_api_'+d.name+'_t':
299 d for d in types + imported_types}
300 self.defines_hash = {d.name: d for d in defines}
303 '''Output the top boilerplate.'''
304 write = self.stream.write
305 write('#ifndef included_{}_api_fromjson_h\n'.format(self.module))
306 write('#define included_{}_api_fromjson_h\n'.format(self.module))
307 write('#include <vppinfra/cJSON.h>\n\n')
308 write('#include <vat2/jsonconvert.h>\n\n')
310 def is_base_type(self, t):
311 '''Check if a type is one of the VPP API base types'''
312 if t in self.is_number:
319 '''Output the bottom boilerplate.'''
320 write = self.stream.write
323 def print_string(self, o, toplevel=False):
324 '''Convert JSON string to vl_api_string_t'''
325 write = self.stream.write
327 msgvar = "a" if toplevel else "mp"
328 msgsize = "l" if toplevel else "*len"
331 write(' char *p = cJSON_GetStringValue(item);\n')
332 write(' size_t plen = strlen(p);\n')
333 write(' {msgvar} = realloc({msgvar}, {msgsize} + plen);\n'
334 .format(msgvar=msgvar, msgsize=msgsize))
335 write(' vl_api_c_string_to_api_string(p, (void *){msgvar} + '
336 '{msgsize} - sizeof(vl_api_string_t));\n'
337 .format(msgvar=msgvar, msgsize=msgsize))
338 write(' {msgsize} += plen;\n'.format(msgsize=msgsize))
340 write(' strncpy_s((char *)a->{n}, sizeof(a->{n}), '
341 'cJSON_GetStringValue(item), sizeof(a->{n}) - 1);\n'
342 .format(n=o.fieldname))
344 def print_field(self, o, toplevel=False):
345 '''Called for every field in a typedef or define.'''
346 write = self.stream.write
347 write(' // start field {}\n'.format(o.fieldname))
348 if o.fieldname in self.noprint_fields:
350 is_bt = self.is_base_type(o.fieldtype)
351 t = 'vl_api_{}'.format(o.fieldtype) if is_bt else o.fieldtype
353 msgvar = "a" if toplevel else "mp"
354 msgsize = "&l" if toplevel else "len"
357 write(' vl_api_{t}_fromjson(item, &a->{n});\n'
358 .format(t=o.fieldtype, n=o.fieldname))
360 write(' {msgvar} = {t}_fromjson({msgvar}, '
361 '{msgsize}, item, &a->{n});\n'
362 .format(t=t, n=o.fieldname, msgvar=msgvar, msgsize=msgsize))
363 write(' if (!{msgvar}) return 0;\n'.format(msgvar=msgvar))
365 write(' // end field {}\n'.format(o.fieldname))
367 _dispatch['Field'] = print_field
369 def print_array(self, o, toplevel=False):
370 '''Convert JSON array to VPP API array'''
371 write = self.stream.write
376 cJSON *array = cJSON_GetObjectItem(o, "{n}");
377 int size = cJSON_GetArraySize(array);
378 if (size != {lfield}) return 0;
379 for (i = 0; i < size; i++) {{
380 cJSON *e = cJSON_GetArrayItem(array, i);
388 cJSON *array = cJSON_GetObjectItem(o, "{n}");
389 int size = cJSON_GetArraySize(array);
391 {msgvar} = realloc({msgvar}, {msgsize} + sizeof({t}) * size);
392 {t} *d = (void *){msgvar} + {msgsize};
393 {msgsize} += sizeof({t}) * size;
394 for (i = 0; i < size; i++) {{
395 cJSON *e = cJSON_GetArrayItem(array, i);
401 if o.fieldtype == 'string':
402 self.print_string(o, toplevel)
405 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
406 msgvar = "a" if toplevel else "mp"
407 msgsize = "l" if toplevel else "*len"
409 if o.fieldtype == 'u8':
411 write(' s = u8string_fromjson(o, "{}");\n'
412 .format(o.fieldname))
413 write(' if (!s) return 0;\n')
414 write(' {} = vec_len(s);\n'.format(lfield))
416 write(' {msgvar} = realloc({msgvar}, {msgsize} + '
417 'vec_len(s));\n'.format(msgvar=msgvar, msgsize=msgsize))
418 write(' memcpy((void *){msgvar} + {msgsize}, s, '
419 'vec_len(s));\n'.format(msgvar=msgvar, msgsize=msgsize))
420 write(' {msgsize} += vec_len(s);\n'.format(msgsize=msgsize))
422 write(' vec_free(s);\n')
424 write(' u8string_fromjson2(o, "{n}", a->{n});\n'
425 .format(n=o.fieldname))
428 is_bt = self.is_base_type(o.fieldtype)
432 call = ('vl_api_{t}_fromjson(e, &d[i]);'
433 .format(t=o.fieldtype))
435 call = ('{t}_fromjson({msgvar}, len, e, &d[i]); '
436 .format(t=o.fieldtype, msgvar=msgvar))
437 write(forloop_vla.format(lfield=lfield,
445 call = ('vl_api_{t}_fromjson(e, &a->{n}[i]);'
446 .format(t=t, n=o.fieldname))
448 call = ('a = {}_fromjson({}, len, e, &a->{}[i]);'
449 .format(t, msgvar, o.fieldname))
450 write(forloop.format(lfield=lfield,
457 _dispatch['Array'] = print_array
459 def print_enum(self, o):
460 '''Convert to JSON enum(string) to VPP API enum (int)'''
461 write = self.stream.write
462 write('static inline void *vl_api_{n}_t_fromjson '
463 '(void *mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n'
465 write(' char *p = cJSON_GetStringValue(o);\n')
467 write(' if (strcmp(p, "{}") == 0) {{*a = {}; return mp;}}\n'
469 write(' return 0;\n')
472 _dispatch['Enum'] = print_enum
474 def print_enum_flag(self, o):
475 '''Convert to JSON enum(string) to VPP API enum (int)'''
476 write = self.stream.write
477 write('static inline void *vl_api_{n}_t_fromjson '
478 '(void *mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n'
482 write(' for (i = 0; i < cJSON_GetArraySize(o); i++) {\n')
483 write(' cJSON *e = cJSON_GetArrayItem(o, i);\n')
484 write(' char *p = cJSON_GetStringValue(e);\n')
485 write(' if (!p) return 0;\n')
487 write(' if (strcmp(p, "{}") == 0) *a |= {};\n'
490 write(' return mp;\n')
493 _dispatch['EnumFlag'] = print_enum_flag
495 def print_typedef(self, o):
496 '''Convert from JSON object to VPP API binary representation'''
497 write = self.stream.write
499 write('static inline void *vl_api_{name}_t_fromjson (void *mp, '
500 'int *len, cJSON *o, vl_api_{name}_t *a) {{\n'
501 .format(name=o.name))
502 write(' cJSON *item __attribute__ ((unused));\n')
503 write(' u8 *s __attribute__ ((unused));\n')
505 if t.type == 'Field' and t.is_lengthfield:
507 write(' item = cJSON_GetObjectItem(o, "{}");\n'
508 .format(t.fieldname))
509 write(' if (!item) return 0;\n')
511 self._dispatch[t.type](self, t)
513 write(' return mp;\n')
516 def print_union(self, o):
517 '''Convert JSON object to VPP API binary union'''
518 write = self.stream.write
520 write('static inline void *vl_api_{name}_t_fromjson (void *mp, '
521 'int *len, cJSON *o, vl_api_{name}_t *a) {{\n'
522 .format(name=o.name))
523 write(' cJSON *item __attribute__ ((unused));\n')
524 write(' u8 *s __attribute__ ((unused));\n')
526 if t.type == 'Field' and t.is_lengthfield:
528 write(' item = cJSON_GetObjectItem(o, "{}");\n'
529 .format(t.fieldname))
530 write(' if (item) {\n')
531 self._dispatch[t.type](self, t)
533 write(' return mp;\n')
536 def print_define(self, o):
537 '''Convert JSON object to VPP API message'''
538 write = self.stream.write
539 write('static inline vl_api_{name}_t *vl_api_{name}_t_fromjson '
540 '(cJSON *o, int *len) {{\n'.format(name=o.name))
541 write(' cJSON *item __attribute__ ((unused));\n')
542 write(' u8 *s __attribute__ ((unused));\n')
543 write(' int l = sizeof(vl_api_{}_t);\n'.format(o.name))
544 write(' vl_api_{}_t *a = malloc(l);\n'.format(o.name))
547 if t.fieldname in self.noprint_fields:
549 if t.type == 'Field' and t.is_lengthfield:
551 write(' // processing {}: {} {}\n'
552 .format(o.name, t.fieldtype, t.fieldname))
554 write(' item = cJSON_GetObjectItem(o, "{}");\n'
555 .format(t.fieldname))
556 write(' if (!item) { free(a); return 0; }\n')
557 self._dispatch[t.type](self, t, toplevel=True)
561 write(' *len = l;\n')
562 write(' return a;\n')
565 def print_using(self, o):
566 '''Convert JSON field to VPP type alias'''
567 write = self.stream.write
573 write('static inline void *vl_api_{name}_t_fromjson (void *mp, '
574 'int *len, cJSON *o, vl_api_{name}_t *a) {{\n'
575 .format(name=o.name))
576 if 'length' in o.alias:
577 if t.fieldtype != 'u8':
578 raise ValueError("Error in processing type {} for {}"
579 .format(t.fieldtype, o.name))
580 write(' vl_api_u8_string_fromjson(o, (u8 *)a, {});\n'
581 .format(o.alias['length']))
583 write(' vl_api_{t}_fromjson(o, ({t} *)a);\n'
584 .format(t=t.fieldtype))
586 write(' return mp;\n')
589 _dispatch['Typedef'] = print_typedef
590 _dispatch['Define'] = print_define
591 _dispatch['Using'] = print_using
592 _dispatch['Union'] = print_union
594 def generate_function(self, t):
595 '''Main entry point'''
596 write = self.stream.write
598 write('/* Manual print {} */\n'.format(t.name))
600 self._dispatch[t.type](self, t)
602 def generate_types(self):
603 '''Main entry point'''
605 self.generate_function(t)
607 def generate_defines(self):
608 '''Main entry point'''
609 for t in self.defines:
610 self.generate_function(t)
613 def generate_tojson(s, modulename, stream):
614 '''Generate all functions to convert from API to JSON'''
617 write('/* Imported API files */\n')
618 for i in s['Import']:
619 f = i.filename.replace('plugins/', '')
620 write('#include <{}_tojson.h>\n'.format(f))
622 pp = ToJSON(modulename, s['types'], s['Define'], s['imported']['types'],
626 pp.generate_defines()
631 def generate_fromjson(s, modulename, stream):
632 '''Generate all functions to convert from JSON to API'''
634 write('/* Imported API files */\n')
635 for i in s['Import']:
636 f = i.filename.replace('plugins/', '')
637 write('#include <{}_fromjson.h>\n'.format(f))
639 pp = FromJSON(modulename, s['types'], s['Define'], s['imported']['types'],
643 pp.generate_defines()
648 ###############################################################################
651 DATESTRING = datetime.datetime.utcfromtimestamp(
652 int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
653 TOP_BOILERPLATE = '''\
655 * VLIB API definitions {datestring}
656 * Input file: {input_filename}
657 * Automatically generated: please edit the input file NOT this file!
661 #if defined(vl_msg_id)||defined(vl_union_id) \\
662 || defined(vl_printfun) ||defined(vl_endianfun) \\
663 || defined(vl_api_version)||defined(vl_typedefs) \\
664 || defined(vl_msg_name)||defined(vl_msg_name_crc_list) \\
665 || defined(vl_api_version_tuple)
666 /* ok, something was selected */
668 #warning no content included from {input_filename}
671 #define VL_API_PACKED(x) x __attribute__ ((packed))
674 BOTTOM_BOILERPLATE = '''\
675 /****** API CRC (whole file) *****/
677 #ifdef vl_api_version
678 vl_api_version({input_filename}, {file_crc:#08x})
685 '''Generate macro to map API message id to handler'''
688 /****** Message ID / handler enum ******/
693 for t in s['Define']:
694 output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % \
695 (t.name.upper(), t.name)
702 '''Generate calls to name mapping macro'''
705 /****** Message names ******/
710 for t in s['Define']:
711 dont_trace = 0 if t.dont_trace else 1
712 output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
718 def msg_name_crc_list(s, suffix):
719 '''Generate list of names to CRC mappings'''
722 /****** Message name, crc list ******/
724 #ifdef vl_msg_name_crc_list
726 output += "#define foreach_vl_msg_name_crc_%s " % suffix
728 for t in s['Define']:
729 output += "\\\n_(VL_API_%s, %s, %08x) " % \
730 (t.name.upper(), t.name, t.crc)
736 def api2c(fieldtype):
737 '''Map between API type names and internal VPP type names'''
738 mappingtable = {'string': 'vl_api_string_t', }
739 if fieldtype in mappingtable:
740 return mappingtable[fieldtype]
744 def typedefs(filename):
745 '''Include in the main files to the types file'''
748 /****** Typedefs ******/
751 #include "{include}.api_types.h"
753 '''.format(include=filename)
757 FORMAT_STRINGS = {'u8': '%u',
770 '''Functions for pretty printing VPP API messages'''
772 noprint_fields = {'_vl_msg_id': None,
773 'client_index': None,
776 def __init__(self, stream):
780 def print_string(o, stream):
781 '''Pretty print a vl_api_string_t'''
784 write(' if (vl_api_string_len(&a->{f}) > 0) {{\n'
785 .format(f=o.fieldname))
786 write(' s = format(s, "\\n%U{f}: %U", '
787 'format_white_space, indent, '
788 'vl_api_format_string, (&a->{f}));\n'.format(f=o.fieldname))
790 write(' s = format(s, "\\n%U{f}:", '
791 'format_white_space, indent);\n'.format(f=o.fieldname))
794 write(' s = format(s, "\\n%U{f}: %s", '
795 'format_white_space, indent, a->{f});\n'
796 .format(f=o.fieldname))
798 def print_field(self, o, stream):
799 '''Pretty print API field'''
801 if o.fieldname in self.noprint_fields:
803 if o.fieldtype in FORMAT_STRINGS:
804 f = FORMAT_STRINGS[o.fieldtype]
805 write(' s = format(s, "\\n%U{n}: {f}", '
806 'format_white_space, indent, a->{n});\n'
807 .format(n=o.fieldname, f=f))
809 write(' s = format(s, "\\n%U{n}: %U", '
810 'format_white_space, indent, '
811 'format_{t}, &a->{n}, indent);\n'
812 .format(n=o.fieldname, t=o.fieldtype))
814 _dispatch['Field'] = print_field
816 def print_array(self, o, stream):
817 '''Pretty print API array'''
821 for (i = 0; i < {lfield}; i++) {{
822 s = format(s, "\\n%U{n}: %U",
823 format_white_space, indent, format_{t}, &a->{n}[i], indent);
827 forloop_format = '''\
828 for (i = 0; i < {lfield}; i++) {{
829 s = format(s, "\\n%U{n}: {t}",
830 format_white_space, indent, a->{n}[i]);
834 if o.fieldtype == 'string':
835 self.print_string(o, stream)
838 if o.fieldtype == 'u8':
840 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
841 'indent, format_hex_bytes, a->{n}, a->{lfield});\n'
842 .format(n=o.fieldname, lfield=o.lengthfield))
844 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
845 'indent, format_hex_bytes, a, {lfield});\n'
846 .format(n=o.fieldname, lfield=o.length))
849 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
850 if o.fieldtype in FORMAT_STRINGS:
851 write(forloop_format.format(lfield=lfield,
852 t=FORMAT_STRINGS[o.fieldtype],
855 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
857 _dispatch['Array'] = print_array
860 def print_alias(k, v, stream):
861 '''Pretty print type alias'''
863 if ('length' in v.alias and v.alias['length'] and
864 v.alias['type'] == 'u8'):
865 write(' return format(s, "%U", format_hex_bytes, a, {});\n'
866 .format(v.alias['length']))
867 elif v.alias['type'] in FORMAT_STRINGS:
868 write(' return format(s, "{}", *a);\n'
869 .format(FORMAT_STRINGS[v.alias['type']]))
871 write(' return format(s, "{} (print not implemented)");\n'
875 def print_enum(o, stream):
876 '''Pretty print API enum'''
878 write(" switch(*a) {\n")
880 write(" case %s:\n" % b[1])
881 write(' return format(s, "{}");\n'.format(b[0]))
884 _dispatch['Enum'] = print_enum
885 _dispatch['EnumFlag'] = print_enum
887 def print_obj(self, o, stream):
891 if o.type in self._dispatch:
892 self._dispatch[o.type](self, o, stream)
894 write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
895 .format(o.type, o.fieldtype, o.fieldname))
898 def printfun(objs, stream, modulename):
899 '''Main entry point for pretty print function generation'''
903 /****** Print functions *****/
905 #ifndef included_{module}_printfun
906 #define included_{module}_printfun
909 #define _uword_fmt \"%lld\"
910 #define _uword_cast (long long)
912 #define _uword_fmt \"%ld\"
913 #define _uword_cast long
919 static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
922 u32 indent __attribute__((unused)) = 2;
923 int i __attribute__((unused));
926 h = h.format(module=modulename)
929 pp = Printfun(stream)
932 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
934 write(signature.format(name=t.name))
935 write(' /* Message definition: vl_api_{}_t: */\n'.format(t.name))
936 write(" s = format(s, \"vl_api_%s_t:\");\n" % t.name)
938 pp.print_obj(o, stream)
939 write(' vec_add1(s, 0);\n')
940 write(' vl_print (handle, (char *)s);\n')
941 write(' vec_free (s);\n')
942 write(' return handle;\n')
946 write("\n#endif /* vl_printfun */\n")
951 def printfun_types(objs, stream, modulename):
952 '''Pretty print API types'''
954 pp = Printfun(stream)
957 /****** Print functions *****/
959 #ifndef included_{module}_printfun_types
960 #define included_{module}_printfun_types
963 h = h.format(module=modulename)
967 static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
969 vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
970 u32 indent __attribute__((unused)) = va_arg (*args, u32);
971 int i __attribute__((unused));
976 if t.__class__.__name__ == 'Enum' or t.__class__.__name__ == 'EnumFlag':
977 write(signature.format(name=t.name))
978 pp.print_enum(t.block, stream)
979 write(' return s;\n')
984 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
987 if t.__class__.__name__ == 'Using':
988 write(signature.format(name=t.name))
989 pp.print_alias(t.name, t, stream)
993 write(signature.format(name=t.name))
995 pp.print_obj(o, stream)
997 write(' return s;\n')
1001 write("\n#endif /* vl_printfun_types */\n")
1004 def generate_imports(imports):
1005 '''Add #include matching the API import statements'''
1006 output = '/* Imported API files */\n'
1007 output += '#ifndef vl_api_version\n'
1010 s = i.filename.replace('plugins/', '')
1011 output += '#include <{}.h>\n'.format(s)
1012 output += '#endif\n'
1017 'u16': 'clib_net_to_host_u16',
1018 'u32': 'clib_net_to_host_u32',
1019 'u64': 'clib_net_to_host_u64',
1020 'i16': 'clib_net_to_host_i16',
1021 'i32': 'clib_net_to_host_i32',
1022 'i64': 'clib_net_to_host_i64',
1023 'f64': 'clib_net_to_host_f64',
1027 def endianfun_array(o):
1028 '''Generate endian functions for arrays'''
1030 for (i = 0; i < {length}; i++) {{
1031 a->{name}[i] = {format}(a->{name}[i]);
1035 forloop_format = '''\
1036 for (i = 0; i < {length}; i++) {{
1037 {type}_endian(&a->{name}[i]);
1042 if o.fieldtype == 'u8' or o.fieldtype == 'string':
1043 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
1045 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
1046 if o.fieldtype in ENDIAN_STRINGS:
1048 .format(length=lfield,
1049 format=ENDIAN_STRINGS[o.fieldtype],
1052 output += (forloop_format
1053 .format(length=lfield, type=o.fieldtype,
1058 NO_ENDIAN_CONVERSION = {'client_index': None}
1061 def endianfun_obj(o):
1062 '''Generate endian conversion function for type'''
1064 if o.type == 'Array':
1065 return endianfun_array(o)
1066 if o.type != 'Field':
1067 output += (' s = format(s, "\\n{} {} {} (print not implemented");\n'
1068 .format(o.type, o.fieldtype, o.fieldname))
1070 if o.fieldname in NO_ENDIAN_CONVERSION:
1071 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
1073 if o.fieldtype in ENDIAN_STRINGS:
1074 output += (' a->{name} = {format}(a->{name});\n'
1075 .format(name=o.fieldname,
1076 format=ENDIAN_STRINGS[o.fieldtype]))
1077 elif o.fieldtype.startswith('vl_api_'):
1078 output += (' {type}_endian(&a->{name});\n'
1079 .format(type=o.fieldtype, name=o.fieldname))
1081 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
1086 def endianfun(objs, modulename):
1087 '''Main entry point for endian function generation'''
1090 /****** Endian swap functions *****/\n\
1092 #ifndef included_{module}_endianfun
1093 #define included_{module}_endianfun
1095 #undef clib_net_to_host_uword
1097 #define clib_net_to_host_uword clib_net_to_host_u64
1099 #define clib_net_to_host_uword clib_net_to_host_u32
1103 output = output.format(module=modulename)
1106 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
1108 int i __attribute__((unused));
1112 if t.__class__.__name__ == 'Enum' or t.__class__.__name__ == 'EnumFlag' :
1113 output += signature.format(name=t.name)
1114 if t.enumtype in ENDIAN_STRINGS:
1115 output += (' *a = {}(*a);\n'
1116 .format(ENDIAN_STRINGS[t.enumtype]))
1118 output += (' /* a->{name} = a->{name} (no-op) */\n'
1119 .format(name=t.name))
1125 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
1128 if t.__class__.__name__ == 'Using':
1129 output += signature.format(name=t.name)
1130 if ('length' in t.alias and t.alias['length'] and
1131 t.alias['type'] == 'u8'):
1132 output += (' /* a->{name} = a->{name} (no-op) */\n'
1133 .format(name=t.name))
1134 elif t.alias['type'] in FORMAT_STRINGS:
1135 output += (' *a = {}(*a);\n'
1136 .format(ENDIAN_STRINGS[t.alias['type']]))
1138 output += ' /* Not Implemented yet {} */'.format(t.name)
1142 output += signature.format(name=t.name)
1145 output += endianfun_obj(o)
1148 output += "\n#endif"
1149 output += "\n#endif /* vl_endianfun */\n\n"
1154 def version_tuple(s, module):
1155 '''Generate semantic version string'''
1157 /****** Version tuple *****/
1159 #ifdef vl_api_version_tuple
1162 if 'version' in s['Option']:
1163 v = s['Option']['version']
1164 (major, minor, patch) = v.split('.')
1165 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
1166 (module, major, minor, patch)
1168 output += "\n#endif /* vl_api_version_tuple */\n\n"
1173 def generate_include_enum(s, module, stream):
1174 '''Generate <name>.api_enum.h'''
1175 write = stream.write
1178 write('typedef enum {\n')
1179 for t in s['Define']:
1180 write(' VL_API_{},\n'.format(t.name.upper()))
1181 write(' VL_MSG_{}_LAST\n'.format(module.upper()))
1182 write('}} vl_api_{}_enum_t;\n'.format(module))
1185 def generate_include_counters(s, stream):
1186 '''Include file for the counter data model types.'''
1187 write = stream.write
1190 csetname = counters.name
1191 write('typedef enum {\n')
1192 for c in counters.block:
1193 write(' {}_ERROR_{},\n'
1194 .format(csetname.upper(), c['name'].upper()))
1195 write(' {}_N_ERROR\n'.format(csetname.upper()))
1196 write('}} vl_counter_{}_enum_t;\n'.format(csetname))
1198 write('extern vl_counter_t {}_error_counters[];\n'.format(csetname))
1201 def generate_include_types(s, module, stream):
1202 '''Generate separate API _types file.'''
1203 write = stream.write
1205 write('#ifndef included_{module}_api_types_h\n'.format(module=module))
1206 write('#define included_{module}_api_types_h\n'.format(module=module))
1208 if 'version' in s['Option']:
1209 v = s['Option']['version']
1210 (major, minor, patch) = v.split('.')
1211 write('#define VL_API_{m}_API_VERSION_MAJOR {v}\n'
1212 .format(m=module.upper(), v=major))
1213 write('#define VL_API_{m}_API_VERSION_MINOR {v}\n'
1214 .format(m=module.upper(), v=minor))
1215 write('#define VL_API_{m}_API_VERSION_PATCH {v}\n'
1216 .format(m=module.upper(), v=patch))
1219 write('/* Imported API files */\n')
1220 for i in s['Import']:
1221 filename = i.filename.replace('plugins/', '')
1222 write('#include <{}_types.h>\n'.format(filename))
1224 for o in s['types'] + s['Define']:
1225 tname = o.__class__.__name__
1226 if tname == 'Using':
1227 if 'length' in o.alias:
1228 write('typedef %s vl_api_%s_t[%s];\n' %
1229 (o.alias['type'], o.name, o.alias['length']))
1231 write('typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name))
1232 elif tname == 'Enum' or tname == 'EnumFlag':
1233 if o.enumtype == 'u32':
1234 write("typedef enum {\n")
1236 write("typedef enum __attribute__((packed)) {\n")
1239 write(" %s = %s,\n" % (b[0], b[1]))
1240 write('} vl_api_%s_t;\n' % o.name)
1241 if o.enumtype != 'u32':
1242 size1 = 'sizeof(vl_api_%s_t)' % o.name
1243 size2 = 'sizeof(%s)' % o.enumtype
1244 err_str = 'size of API enum %s is wrong' % o.name
1245 write('STATIC_ASSERT(%s == %s, "%s");\n'
1246 % (size1, size2, err_str))
1248 if tname == 'Union':
1249 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n"
1252 write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
1255 if b.type == 'Option':
1257 if b.type == 'Field':
1258 write(" %s %s;\n" % (api2c(b.fieldtype),
1260 elif b.type == 'Array':
1262 write(" %s %s[0];\n" % (api2c(b.fieldtype),
1265 # Fixed length strings decay to nul terminated u8
1266 if b.fieldtype == 'string':
1269 .format(api2c(b.fieldtype),
1272 write(' u8 {}[{}];\n'
1273 .format(b.fieldname, b.length))
1275 write(" %s %s[%s];\n" %
1276 (api2c(b.fieldtype), b.fieldname,
1279 raise ValueError("Error in processing type {} for {}"
1282 write('} vl_api_%s_t;\n' % o.name)
1284 for t in s['Define']:
1285 write('#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'
1286 .format(n=t.name, ID=t.name.upper(), crc=t.crc))
1291 def generate_c_boilerplate(services, defines, counters, file_crc,
1293 '''VPP side plugin.'''
1294 write = stream.write
1295 define_hash = {d.name: d for d in defines}
1298 #define vl_endianfun /* define message structures */
1299 #include "{module}.api.h"
1302 /* instantiate all the print functions we know about */
1303 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
1305 #include "{module}.api.h"
1310 write(hdr.format(module=module))
1311 write('static u16\n')
1312 write('setup_message_id_table (void) {\n')
1313 write(' api_main_t *am = my_api_main;\n')
1314 write(' vl_msg_api_msg_config_t c;\n')
1315 write(' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", '
1316 'VL_MSG_{m}_LAST);\n'
1317 .format(module, crc=file_crc, m=module.upper()))
1320 write(' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
1321 ' VL_API_{ID} + msg_id_base);\n'
1322 .format(n=d.name, ID=d.name.upper(), crc=d.crc))
1324 d = define_hash[s.caller]
1325 write(' c = (vl_msg_api_msg_config_t) '
1326 ' {{.id = VL_API_{ID} + msg_id_base,\n'
1328 ' .handler = vl_api_{n}_t_handler,\n'
1329 ' .cleanup = vl_noop_handler,\n'
1330 ' .endian = vl_api_{n}_t_endian,\n'
1331 ' .print = vl_api_{n}_t_print,\n'
1332 ' .is_autoendian = 0}};\n'
1333 .format(n=s.caller, ID=s.caller.upper()))
1334 write(' vl_msg_api_config (&c);\n')
1336 d = define_hash[s.reply]
1337 write(' c = (vl_msg_api_msg_config_t) '
1338 '{{.id = VL_API_{ID} + msg_id_base,\n'
1341 ' .cleanup = vl_noop_handler,\n'
1342 ' .endian = vl_api_{n}_t_endian,\n'
1343 ' .print = vl_api_{n}_t_print,\n'
1344 ' .is_autoendian = 0}};\n'
1345 .format(n=s.reply, ID=s.reply.upper()))
1346 write(' vl_msg_api_config (&c);\n')
1350 write(' return msg_id_base;\n')
1353 severity = {'error': 'VL_COUNTER_SEVERITY_ERROR',
1354 'info': 'VL_COUNTER_SEVERITY_INFO',
1355 'warn': 'VL_COUNTER_SEVERITY_WARN'}
1357 for cnt in counters:
1359 write('vl_counter_t {}_error_counters[] = {{\n'.format(csetname))
1362 write(' .name = "{}",\n'.format(c['name']))
1363 write(' .desc = "{}",\n'.format(c['description']))
1364 write(' .severity = {},\n'.format(severity[c['severity']]))
1369 def generate_c_test_boilerplate(services, defines, file_crc, module, plugin,
1371 '''Generate code for legacy style VAT. To be deleted.'''
1372 write = stream.write
1374 define_hash = {d.name: d for d in defines}
1377 #define vl_endianfun /* define message structures */
1378 #include "{module}.api.h"
1381 /* instantiate all the print functions we know about */
1382 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
1384 #include "{module}.api.h"
1389 write(hdr.format(module=module))
1392 d = define_hash[s.reply]
1397 ' * Manual definition requested for: \n'
1398 ' * vl_api_{n}_t_handler()\n'
1402 if not define_hash[s.caller].autoreply:
1403 write('/* Generation not supported (vl_api_{n}_t_handler()) */\n'
1406 write('#ifndef VL_API_{n}_T_HANDLER\n'.format(n=s.reply.upper()))
1407 write('static void\n')
1408 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'
1410 write(' vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
1411 write(' i32 retval = ntohl(mp->retval);\n')
1412 write(' if (vam->async_mode) {\n')
1413 write(' vam->async_errors += (retval < 0);\n')
1414 write(' } else {\n')
1415 write(' vam->retval = retval;\n')
1416 write(' vam->result_ready = 1;\n')
1422 if define_hash[e].manual_print:
1424 write('static void\n')
1425 write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
1426 write(' vl_print(0, "{n} event called:");\n'.format(n=e))
1427 write(' vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
1430 write('static void\n')
1431 write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
1433 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, '
1435 ' vl_api_{n}_t_handler, '
1436 ' vl_noop_handler,\n'
1437 ' vl_api_{n}_t_endian, '
1438 ' vl_api_{n}_t_print,\n'
1439 ' sizeof(vl_api_{n}_t), 1);\n'
1440 .format(n=s.reply, ID=s.reply.upper()))
1441 write(' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'
1442 .format(n=s.caller))
1444 write(' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
1446 help=define_hash[s.caller].options['vat_help']))
1452 write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, '
1454 ' vl_api_{n}_t_handler, '
1455 ' vl_noop_handler,\n'
1456 ' vl_api_{n}_t_endian, '
1457 ' vl_api_{n}_t_print,\n'
1458 ' sizeof(vl_api_{n}_t), 1);\n'
1459 .format(n=e, ID=e.upper()))
1463 write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
1465 write('clib_error_t * vat_{}_plugin_register (vat_main_t *vam)\n'
1468 write(' {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
1469 write(' mainp->vat_main = vam;\n')
1470 write(' mainp->msg_id_base = vl_client_get_first_plugin_msg_id '
1471 ' ("{n}_{crc:08x}");\n'
1472 .format(n=module, crc=file_crc))
1473 write(' if (mainp->msg_id_base == (u16) ~0)\n')
1474 write(' return clib_error_return (0, "{} plugin not loaded...");\n'
1476 write(' setup_message_id_table (vam, mainp->msg_id_base);\n')
1477 write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
1478 write(' VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
1480 write(' return 0;\n')
1485 '''Check if a method is generated already.'''
1486 def _f(module, d, processed, *args):
1487 if d.name in processed:
1489 processed[d.name] = True
1490 return func(module, d, *args)
1494 def c_test_api_service(s, dump, stream):
1495 '''Generate JSON code for a service.'''
1496 write = stream.write
1498 req_reply_template = '''\
1505 mp = vl_api_{n}_t_fromjson(o, &len);
1507 fprintf(stderr, "Failed converting JSON to API\\n");
1511 mp->_vl_msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1512 vl_api_{n}_t_endian(mp);
1513 vac_write((char *)mp, len);
1519 vac_read(&p, &l, 5); // XXX: Fix timeout
1520 // XXX Will fail in case of event received. Do loop
1521 if (ntohs(*((u16 *)p)) != vac_get_msg_index(VL_API_{R}_CRC)) {{
1522 fprintf(stderr, "Mismatched reply\\n");
1525 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1526 vl_api_{r}_t_endian(rmp);
1527 return vl_api_{r}_t_tojson(rmp);
1531 dump_details_template = '''\
1535 u16 msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1538 vl_api_{n}_t *mp = vl_api_{n}_t_fromjson(o, &len);
1540 fprintf(stderr, "Failed converting JSON to API\\n");
1543 mp->_vl_msg_id = msg_id;
1544 vl_api_{n}_t_endian(mp);
1545 vac_write((char *)mp, len);
1548 vat2_control_ping(123); // FIX CONTEXT
1549 cJSON *reply = cJSON_CreateArray();
1551 u16 ping_reply_msg_id = vac_get_msg_index(VL_API_CONTROL_PING_REPLY_CRC);
1552 u16 details_msg_id = vac_get_msg_index(VL_API_{R}_CRC);
1558 vac_read(&p, &l, 5); // XXX: Fix timeout
1560 /* Message can be one of [_details, control_ping_reply
1561 * or unrelated event]
1563 u16 reply_msg_id = ntohs(*((u16 *)p));
1564 if (reply_msg_id == ping_reply_msg_id) {{
1568 if (reply_msg_id == details_msg_id) {{
1569 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1570 vl_api_{r}_t_endian(rmp);
1571 cJSON_AddItemToArray(reply, vl_api_{r}_t_tojson(rmp));
1578 gets_details_reply_template = '''\
1582 u16 msg_id = vac_get_msg_index(VL_API_{N}_CRC);
1585 vl_api_{n}_t *mp = vl_api_{n}_t_fromjson(o, &len);
1587 fprintf(stderr, "Failed converting JSON to API\\n");
1590 mp->_vl_msg_id = msg_id;
1592 vl_api_{n}_t_endian(mp);
1593 vac_write((char *)mp, len);
1596 cJSON *reply = cJSON_CreateArray();
1598 u16 reply_msg_id = vac_get_msg_index(VL_API_{R}_CRC);
1599 u16 details_msg_id = vac_get_msg_index(VL_API_{D}_CRC);
1605 vac_read(&p, &l, 5); // XXX: Fix timeout
1607 /* Message can be one of [_details, control_ping_reply
1608 * or unrelated event]
1610 u16 msg_id = ntohs(*((u16 *)p));
1611 if (msg_id == reply_msg_id) {{
1612 vl_api_{r}_t *rmp = (vl_api_{r}_t *)p;
1613 vl_api_{r}_t_endian(rmp);
1614 cJSON_AddItemToArray(reply, vl_api_{r}_t_tojson(rmp));
1618 if (msg_id == details_msg_id) {{
1619 vl_api_{d}_t *rmp = (vl_api_{d}_t *)p;
1620 vl_api_{d}_t_endian(rmp);
1621 cJSON_AddItemToArray(reply, vl_api_{d}_t_tojson(rmp));
1630 if s.stream_message:
1631 write(gets_details_reply_template
1632 .format(n=s.caller, r=s.reply, N=s.caller.upper(),
1633 R=s.reply.upper(), d=s.stream_message,
1634 D=s.stream_message.upper()))
1636 write(dump_details_template.format(n=s.caller, r=s.reply,
1640 write(req_reply_template.format(n=s.caller, r=s.reply,
1645 def generate_c_test2_boilerplate(services, defines, module, stream):
1646 '''Generate code for VAT2 plugin.'''
1647 write = stream.write
1649 define_hash = {d.name: d for d in defines}
1653 #include <vlibapi/api.h>
1654 #include <vlibmemory/api.h>
1655 #include <vppinfra/error.h>
1656 #include <vnet/ip/ip_format_fns.h>
1657 #include <vnet/ethernet/ethernet_format_fns.h>
1659 #define vl_typedefs /* define message structures */
1660 #include <vpp/api/vpe_all_api_h.h>
1663 #include "{module}.api_enum.h"
1664 #include "{module}.api_types.h"
1666 #define vl_endianfun /* define message structures */
1667 #include "{module}.api.h"
1670 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
1672 #include "{module}.api.h"
1675 #include "{module}.api_tojson.h"
1676 #include "{module}.api_fromjson.h"
1677 #include <vpp-api/client/vppapiclient.h>
1679 #include <vat2/vat2_helpers.h>
1683 write(hdr.format(module=module))
1686 if s.reply not in define_hash:
1688 c_test_api_service(s, s.stream, stream)
1690 write('void vat2_register_function(char *, cJSON * (*)(cJSON *));\n')
1691 # write('__attribute__((constructor))')
1692 write('clib_error_t *\n')
1693 write('vat2_register_plugin (void) {\n')
1695 write(' vat2_register_function("{n}", api_{n});\n'
1696 .format(n=s.caller))
1697 write(' return 0;\n')
1702 # Plugin entry point
1704 def run(args, apifilename, s):
1705 '''Main plugin entry point.'''
1708 if not args.outputdir:
1709 sys.stderr.write('Missing --outputdir argument')
1712 basename = os.path.basename(apifilename)
1713 filename, _ = os.path.splitext(basename)
1714 modulename = filename.replace('.', '_')
1715 filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
1716 filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
1717 filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
1718 filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
1719 filename_c_test2 = (os.path.join(args.outputdir + '/' + basename +
1721 filename_c_tojson = (os.path.join(args.outputdir +
1722 '/' + basename + '_tojson.h'))
1723 filename_c_fromjson = (os.path.join(args.outputdir + '/' +
1724 basename + '_fromjson.h'))
1726 # Generate separate types file
1728 generate_include_types(s, modulename, st)
1729 with open(filename_types, 'w') as fd:
1731 shutil.copyfileobj(st, fd)
1734 # Generate separate enum file
1736 st.write('#ifndef included_{}_api_enum_h\n'.format(modulename))
1737 st.write('#define included_{}_api_enum_h\n'.format(modulename))
1738 generate_include_enum(s, modulename, st)
1739 generate_include_counters(s['Counters'], st)
1740 st.write('#endif\n')
1741 with open(filename_enum, 'w') as fd:
1743 shutil.copyfileobj(st, fd)
1746 # Generate separate C file
1748 generate_c_boilerplate(s['Service'], s['Define'], s['Counters'],
1749 s['file_crc'], modulename, st)
1750 with open(filename_c, 'w') as fd:
1752 shutil.copyfileobj(st, fd)
1755 # Generate separate C test file
1757 plugin = bool('plugin' in apifilename)
1758 generate_c_test_boilerplate(s['Service'], s['Define'],
1760 modulename, plugin, st)
1761 with open(filename_c_test, 'w') as fd:
1763 shutil.copyfileobj(st, fd)
1766 # Fully autogenerated VATv2 C test file
1768 generate_c_test2_boilerplate(s['Service'], s['Define'],
1770 with open(filename_c_test2, 'w') as fd:
1772 shutil.copyfileobj(st, fd)
1775 # Generate separate JSON file
1777 generate_tojson(s, modulename, st)
1778 with open(filename_c_tojson, 'w') as fd:
1780 shutil.copyfileobj(st, fd)
1783 generate_fromjson(s, modulename, st)
1784 with open(filename_c_fromjson, 'w') as fd:
1786 shutil.copyfileobj(st, fd)
1789 output = TOP_BOILERPLATE.format(datestring=DATESTRING,
1790 input_filename=basename)
1791 output += generate_imports(s['Import'])
1792 output += msg_ids(s)
1793 output += msg_names(s)
1794 output += msg_name_crc_list(s, filename)
1795 output += typedefs(modulename)
1796 printfun_types(s['types'], stream, modulename)
1797 printfun(s['Define'], stream, modulename)
1798 output += stream.getvalue()
1800 output += endianfun(s['types'] + s['Define'], modulename)
1801 output += version_tuple(s, basename)
1802 output += BOTTOM_BOILERPLATE.format(input_filename=basename,
1803 file_crc=s['file_crc'])